user7836391
user7836391

Reputation: 41

bind() - how to call bind() multiple times on the same socket

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.

Upvotes: 1

Views: 6094

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598011

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.

Upvotes: 4

user207421
user207421

Reputation: 311039

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.

Upvotes: 0

Related Questions