Using boost :: asio is a portable way to find out the port number.

I am currently trying to find a way to find the free port number to establish a connection, ideally with boost :: asio. This port number will be used for listening (and only then can I open the socket).

Roughly, is there any way to do

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

when the port is left empty (setting it to 0 does not work)

None of the options shown previously were portable or effective.

+8
c ++ boost port sockets tcp
source share
1 answer

The best way to deal with this is to simply let the OS select an arbitrary available port at a time when the socket is bound to a port. Tell the socket to bind to port 0, then request the socket for the actual port associated with it, if successful. Do not try to find the port ahead of time, and then become attached to it, which introduces the condition of the race. Another socket can hook the port after you find it, but before you can bind it.

+9
source share

All Articles