Reputation: 1099
There have been other questions regarding the subject of verifying the accessibility and accessibility of socket ports.
How would one go about looking for a port to listen on dynamically in C/C++?
The basic process I'm trying to accomplish is this:
I know you can accomplish something like this if you pick an arbitrary port number and try binding to it. If it fails, increment the number and try again until you get a successful 'bind'.
Is there a more elegant way to do this? It seems kind of hacky.
Upvotes: 3
Views: 6970
Reputation: 536
If you bind to port 0, a random port will be allocated. Then getsockname()
may be used to find out the actual port used.
Upvotes: 13