How to bind to any available port?

SocketsNetworking

Sockets Problem Overview


I need an app that sends an UDP packet to some network server and receives the response. The server replies to the same port number where request came from, so I first need to bind() my socket to any UDP port number.

Hardcoding the UDP port number is a bad idea, as it might be used by any other application running on the same PC.

Is there a way to bind an UDP socket to any port available? IMO it should be an effective way to quickly obtain a free port #, which is used by e.g. accept() function.

If no, then what's the best strategy to try binding and check for WSAEADDRINUSE/EADDRINUSE status: try the ports sequentially starting from from 1025, or 1025+rand(), or some other?

Sockets Solutions


Solution 1 - Sockets

Another option is to specify port 0 to bind(). That will allow you to bind to a specific IP address (in case you have multiple installed) while still binding to a random port. If you need to know which port was picked, you can use getsockname() after the binding has been performed.

Solution 2 - Sockets

Call sendto without calling bind first, the socket will be bound automatically (to a free port).

Solution 3 - Sockets

I must be missing something, why don't you use the udp socket to send back data? Start with sendto and then use recvfrom function to read incoming data also you get as a bonus the address from which the data was sent, right there for you to send a response back.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoontsView Question on Stackoverflow
Solution 1 - SocketsRemy LebeauView Answer on Stackoverflow
Solution 2 - SocketsavakarView Answer on Stackoverflow
Solution 3 - SocketsJonkeView Answer on Stackoverflow