views:

886

answers:

3

Suppose I want to run a TCP/IP service on some port for IPC. As I'm passing the port number to the processes I want to communicate with anyway, the port number doesn't matter. What's the best way to get a random, high (usually >49152) port number that is still available from the system? Is there something in POSIX I can use?

I know FTP servers need this frequently.

A: 

The only way is to loop through the desired port range, attempting to bind a socket to each port one at a time until you find one that is successful.

Remy Lebeau - TeamB
+7  A: 

If you don't specify a port number the OS will pick automatically an ephemeral port number for you.

From Choosing the Port Number:

New server software should strive to avoid depending on a specific port number, especially if it is user-level software that is not ineluctably tied to a well-known port. Fortunately, this is easily done by requesting port 0, which instructs the system to choose an ephemeral port number.

lothar
Yes, port 0 allows the OS to pick a random available port for you. On the other hand, using port 0 does not allow you to specify a range of ports for the OS to pick from. If you are behind a firewall/router, for instance, then being able to use port ranges becomes more important.
Remy Lebeau - TeamB
+2  A: 

Ephemeral ports can do that. Your OS will assign you a port from the free port pool.

There is some C code, BSD-licensed, doing this here

In Python, you can specify a ('127.0.0.1', 0) socket.AF_INET address pair for the same purpose.

NicDumZ