Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How boost.asio discover which port is my server app listening on?

it is a little bit strange to me that boost.asio doesn`t use basic concept when client app connecting to the server - using IP address and port. May be I am a little bit noobie in Boost - and I accept that - but anyway I do not understand.
So, I have code like this to get client connected to the server on the localhost:


        boost::asio::io_service io_service;
        tcp::resolver resolver(io_service);
        tcp::resolver::query query("localhost", "daytime"); 
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); 
        tcp::resolver::iterator end;

        tcp::socket socket(io_service);
        boost::system::error_code error = boost::asio::error::host_not_found;
        while(error && endpoint_iterator != end) {
            socket.close();
            socket.connect(*endpoint_iterator++, error);
        }

Windows in its WinSock 2.0 uses two parameters - IP and port - to identify the server.
So, the qurestion is - how exactly Asio finds out which port is server listening to connections on? Does it scans all ports? And, if it does, what will happen if two servers listening on different ports at the same time?

like image 283
chester89 Avatar asked Feb 23 '09 18:02

chester89


2 Answers

Try,

tcp::resolver::query query("localhost", boost::lexical_cast<string>(port));//assuming port is an int

To answer your question, recall that you are starting the server on port 13. This happens to be the port which runs the Linux daytime service (http://www.sorgonet.com/linux/linuxdaemons/). Hence, they are subsequently able to use query("localhost","daytime") rather than specifying the port.

like image 53
Imran.Fanaswala Avatar answered Nov 17 '22 10:11

Imran.Fanaswala


You are telling it that you want to connect to localhost on the port used by the daytime service. It will look up the appropriate port number in the services file (usually C:\WINDOWS\system32\drivers\etc\services under Windows, I believe /etc/services under Unix). You could also use an explicit port number there.

like image 29
Ferruccio Avatar answered Nov 17 '22 09:11

Ferruccio