I want to start a server which listen to a port. I can specify port explicitly and it works. But I would like to find a port in an automatic way. In this respect I have two questions.
-
In which range of port numbers should I search for? (I used ports 12345, 12346, and 12347 and it was fine).
-
How can I find out if a given port is not occupied by another software?
If you don’t mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.
If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:
Could be used like so: