Using boost::asio is there a portable way to find

2019-06-17 01:43发布

问题:

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.

回答1:

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.