Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind to any available port?

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?

like image 353
Soonts Avatar asked Jul 02 '09 16:07

Soonts


People also ask

How do I bind a port?

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.

Can client bind to a port?

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.

What does bind to port?

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 will happen when you bind port 0?

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.


2 Answers

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.

like image 132
Remy Lebeau Avatar answered Nov 16 '22 00:11

Remy Lebeau


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

like image 23
avakar Avatar answered Nov 16 '22 01:11

avakar