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?
Binding to port 0 is the official documented way to bind to a OS-assigned random port. It is in the bind() documentation: "if the port is specified as zero, the service provider assigns a unique port to the application from the dynamic client port range.
Bind can be used to attach names to a sockets. Thus, say you create a software that uses a particular TCP port, you need to bind it and then, you will know the TCP port it is using.
A port binding is the configuration information that determines where and how a message will be sent or received. Depending on its type, a port binding might refer to physical locations, pipelines, or other orchestrations.
What this means is that if you bind on port 0 and actually bind to port 55441, then the next process that tries to bind to port 0 will probably get port 55442 (if it's available), and the next process will get port 55443, and so on.
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.
Call sendto
without calling bind
first, the socket will be bound automatically (to a free port).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With