I use bind() on an address to which I have set port value equal to 0. I know that in this way, it is bind a random port to the address. But I want that only port with value x such that (x >= 0 && x <= 1023) || (x >= 49152) were choosen, but I noticed that, among random port that can be choosen, there are also port > 49152 . However, if I re-call bind() , it gives error: invalid argument. How can I re-call bind() function without it gives the invalid argument error, or how to solve this problem in another way? Thanks a lot in advance.
-
Your question is about [tag:tcp], not [tag:UNIX-sockets]. – user207421 Apr 10 '17 at 19:15
-
2If you know which port you'd like to bind() to, you might as well supply that port to the bind() call instead of 0. If the port's already in use, the bind() call will fail and then you can try again with a different port number. – Jeremy Friesner Apr 10 '17 at 19:21
-
@EJP It seems `unix-sockets` is a perfectly fine tag, nowhere does it state that it's about TCP; it could just as well be about UDP sockets. – nh2 Oct 08 '17 at 15:44
2 Answers
You cannot call bind()
again on a socket that is already bound. Once a socket is bound, its binding cannot be changed.
Binding to port 0 will bind to an available random ephemeral port, and the range of ephemeral ports is controlled by the OS, not the application. Some OSes do provide configuration values to set the range, but you need to be an admin to change it.
To do what you are looking for, do not bind to port 0 at all. Bind to a specific desired port instead, and if it is not available then bind()
will fail and you can handle the error by calling bind()
again with a different port, repeating as needed until a binding is successful or you have exhausted your list of desired ports.

- 555,201
- 31
- 458
- 770
You can't. You have to close the socket and start again. You can't be so picky about what port you get. They system will give you whatever it gives you.

- 305,947
- 44
- 307
- 483
-
Sometimes, it does make sense to be picky. For example, an FTP server may want to use only a small range of ports for `PASV` transfers, so it has to be able to control the lower and upper values of the port range. – Remy Lebeau Apr 10 '17 at 21:12
-
@RemyLebeau In which case you should cycle through *those* ports trying to bind until you succeed. Binding to port *zero* and then whingeing about the result is futile, essentially a contradiction in terms. – user207421 Apr 11 '17 at 02:58