Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically choosing port number?

Tags:

java

tcp

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?

like image 256
python dude Avatar asked Feb 09 '10 18:02

python dude


1 Answers

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
like image 81
Chris Jester-Young Avatar answered Sep 22 '22 16:09

Chris Jester-Young