views:

1086

answers:

3

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 status: try the ports sequentially starting from from 1025, or 1025+rand(), or some other?

Thanks in advance.

+11  A: 

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

avakar
10x, it worked.
Soonts
A: 

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.

Jonke
+5  A: 

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

Remy Lebeau - TeamB