How to bind to any available port?

networking, sockets

Solution

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

Problem

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?

Original source

Related problems