55
votes

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?

3
accept() is used in connection based sockets, not datagram ones.Beano
maybe this will help: serverfault.com/questions/447044yegor256

3 Answers

42
votes

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

247
votes

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.

-1
votes

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.