Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A bind with a port of zero will bind you to a free port. Is this portable? [closed]

I want my program to bind to a free port.

Google told me that a bind with port=0 will do that, but I haven't found if this is guaranteed to work on any system (Windows/Linux in particular).

Can someone link a doc that say that?

like image 332
MicheleA Avatar asked May 05 '11 09:05

MicheleA


2 Answers

It's standard, documented behavior for AF_INET address family:

http://man7.org/linux/man-pages/man7/ip.7.html

See ip_local_port_range, which contains the following:

    An ephemeral port is allocated to a socket in the following circumstances:

          *  the port number in a socket address is specified as 0 when
             calling bind(2);
like image 126
Jeff Learman Avatar answered Sep 28 '22 14:09

Jeff Learman


It's universal as far as I know, but I can't find any text in the standards that says it is. An alternative that might be more portable is using getaddrinfo with null service name pointers and the AI_PASSIVE flag. This is guaranteed to give you an sockaddr you can bind to. It's also the correct way to let the administrator choose which local ip (v4 or v6) address to bind to.

like image 45
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 15:09

R.. GitHub STOP HELPING ICE