Dynamic port number selection?

In Java, I need to take the port number for communication between multiple instances of the same program. Now I could just pick a fixed number and go with it. But I am wondering if there is a way to dynamically select the port number, so I don’t need to bother my users with the port number setting.

Here was one idea that works as follows:

  • There is a fixed starting port number A.
  • MyApp starts up, trying to capture port A.
  • If this succeeds, then this is the first instance of "MyApp". Done.
  • If this fails, it asks through port A whether the program on A is an instance of "MyApp". If so, communicate with this instance. Done. If not, try to capture port A + 1. And if there is another program using this port (and not an instance of "MyApp"), then take A + 2, then A + 3, etc.

Does this strategy make sense? Or is there a better way to dynamically select a port number?

+7
java tcp
source share
3 answers

If you bind to port 0, Java will use the system port. :-) So, this is probably the easiest way to backtrack if your desired port is already in use.

ServerSocket s = new ServerSocket(0); int port = s.getLocalPort(); // returns the port the system selected 
+27
source share

I would take the inverse and allocate a fixed high port for your application. Make this a configuration value so that it can be changed if necessary. This will simplify setup as often as application users need to request network operations to open ports. Work with assigned IANA values:

http://www.iana.org/assignments/port-numbers

Scan ports can turn your application into a poor citizen for many intrusion detection systems.

+3
source share

You can use Bonjour / ZeroConf to advertise the services of each instance and enable the instance to search for others. Think of it as a directory service that can help manage the port namespace.

Each instance can simply capture a dynamically assigned port in this case. A request to bind to port "0" will usually tell the system to assign a dynamic port.

+1
source share

All Articles