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:
Does this strategy make sense? Or is there a better way to dynamically choose a port number?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With