rabusmar
rabusmar

Reputation: 4143

Get random port for UDP socket

I need to create a program that will communicate with other programs on the same computer via UDP sockets. It will read commands from stdin, and some of this commands will make it to send/receive packets without halting execution. I've read some information out there, but since I'm not familiar with socket programming and need to get this done quickly, I have the following questions:

  1. I need to get a random unused port for the program to listen to, and reserve it so other programs can communicate with this and also the port isn't reserved by another program. I also need to store the port number on a variable for future usage.
  2. Since the communication is across processes on the same machine, I'm wondering if I can use PF_LOCAL.

Also a code sample of the setup of such socket would be welcome, as well as an example of sending/receiving character strings.

Upvotes: 14

Views: 20835

Answers (3)

Mikhail Korobov
Mikhail Korobov

Reputation: 22238

Answer by Remy Lebeau is good if you need a temporary port. It is not so good if you need a persistent reserved port because other software also uses the same method to get a port (including OS TCP stack that needs a new temporary port for each connection).

So the following might happen:

  1. You call bind with 0 and getsockname() to get a port;
  2. then save it into config (or into several configs) for future uses;
  3. software that needs this port starts and binds the port.

Then you need to e.g. restart the software:

  1. software stops and unbinds the port: the port can now be returned by bind(0) and getsockname() again;
  2. e.g. TCP stack needs a port and binds your port;
  3. software can't start because port is already bound.

So for "future uses" you need a port that is not in ephemeral port range (that's the range from which bind(host, 0) returns a port).

My solution for this issue is the port-for command-line utility.

Upvotes: 1

dbeer
dbeer

Reputation: 7203

If it being a random port is actually important, you should do something like:

srand(time(NULL));
rand() % NUM_PORTS; // NUM_PORTS isn't a system #define

Then specify that port in bind. If it fails, pick a new one (no need to re-seed the random generator. If the random port isn't important, look at Remy Lebeau's answer.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595887

Call bind() specifying port 0. That will allow the OS to pick an unused port. You can then use getsockname() to retreive the chosen port.

Upvotes: 28

Related Questions