Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boost::asio is there a portable way to find out free port number

I'm currently trying to figure out a way to find the number of a free port to establish a connection, ideally with boost::asio. This port number would then be used to listen on (and only then can I open a socket).

Roughly, is there a way to do

   tcp::resolver::query query("localhost", port); 

where the port is left blank (setting it to 0 doesn't work)

None of the options seen previously were portable, or efficient.

like image 795
user1018513 Avatar asked Dec 05 '12 23:12

user1018513


1 Answers

The best way to handle this is to just let the OS pick a random available port at the moment that the socket is being bound to a port. Tell the socket to bind to port 0, then query the socket for the actual port it bound to if successful. Do not try to find a port ahead of time and then bind to it, that introduces a race condition. Another socket could snag the port after you found it but before you could bind it.

like image 56
Remy Lebeau Avatar answered Oct 19 '22 23:10

Remy Lebeau