Home  +  Forums  +  C++ and Sockets  +  C++ and SQL: MySQL, sqlite, ODBC  +  Miscellaneous Projects
Logo
~Sockets~
~New~
~Examples~
~Contact~

C++ Socket library tutorial

Using GetPort

Prev   |   Menu   |   Next

If more than one ListenSocket spawns the same socket class, this is a way to find out which ListenSocket is the 'parent' of the new socket.

Original question

I have a problem I cannot solve: I want to have more listening sockets on the same local ip address but on different ports, say on port 1024 and 1025. I have a SocketHandler instance and 2 ListenSocket<MyHttpSocket> but when an incoming connection is being accepted and a new instance of my MyHttpSocket is created I'm no more able to know on which port the connection request arrived, 1024 or 1025. Moreover I cannot start 2 server processes, one on each port, because of other reasons that'll take too long to explain...

getportdemo.cpp
#include <StdoutLog.h>
#include <SocketHandler.h>
#include <TcpSocket.h>
#include <ListenSocket.h>
#include <Utility.h>


class MySocket : public TcpSocket
{
public:
	MySocket(ISocketHandler& h) : TcpSocket(h) {
	}
	void OnAccept() {
		int port = GetParent() -> GetPort();
		Send("I'm the server at port " + 
			Utility::l2string(port) + "\n");
		SetCloseAndDelete();
	}
};


int main()
{
	StdoutLog log;
	SocketHandler h(&log);

	// first server
	ListenSocket<MySocket> l1(h);
	l1.Bind(1024);
	h.Add(&l1);

	// second server
	ListenSocket<MySocket> l2(h);
	l2.Bind(1025);
	h.Add(&l2);

	h.Select(1, 0);
	bool quit = false;
	while (!quit)
	{
		h.Select(1,0);
	}
}

Prev   |   Menu   |   Next

Valid HTML 4.01!

Validate
Page, code, and content Copyright (C) 2021 by Anders Hedström