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?
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?
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:
It's certainly "standard" in the 4.2BSD socket API from which most every other implementation is derived, but I'm not aware of any formal specification that actually says so.
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 theAI_PASSIVE
flag. This is guaranteed to give you ansockaddr
you canbind
to. It's also the correct way to let the administrator choose which local ip (v4 or v6) address to bind to.