tags:

views:

67

answers:

3

In Java, I need to grab a port number for communication between multiple instances of the same program. Now, I could simply pick some fixed number and go with it. But I'm wondering if there's a way to dynamically choose the port number, so that I don't have to bother my users with setting the port number.

Here's one idea I had, which works like this:

  • There's a fixed initial port number A.
  • Program 'MyApp' starts, tries to grab port A.
  • If it succeeds, then it's the first instance of 'MyApp'. Done.
  • If it fails, it asks over port A whether the program on A is an instance of 'MyApp'. If yes, communicate with that instance. Done. If not, try to grab port A+1. And if there's another program using that port (not an instance of 'MyApp' either), then grab A+2, then A+3, and so on.

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

+4  A: 

If you bind to port 0, Java will use a system-generated port. :-) So, that's probably the easiest way to fall back if your desired port is already used.

ServerSocket s = new ServerSocket(0);
int port = s.getLocalPort();    // returns the port the system selected
Chris Jester-Young
... and how will the instances find each other? Isn't that what the question is all about?
jldupont
+2  A: 

I would take the inverse and select a fixed high port for your app. Make it a config value so it could be changed if necessary. This will simplify configuration as often times users of apps need to request network operations to open ports. Work around the IANA assigned values:

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

Scanning ports could turn your app into a bad citizen for many intrusion detection systems.

Nissan Fan
+1  A: 

You could use Bonjour/ZeroConf to advertise the services of each instance and enable an instance to find the others. Think of this as a directory service which could help manage your port namespace.

Each instance can just grab a dynamically assigned port in this case. A request for binding to port "0" will usually instruct the system to assign a dynamic port.

jldupont