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?