I want to find an open local port in some range.
How can I do that in the most efficient way, without connecting to the port.
If you would like to test ports on your computer, use the Windows command prompt and the CMD command netstat -ano. Windows will show you all currently existing network connections via open ports or open, listening ports that are currently not establishing a connection.
Scanning specific port ranges There are several ways of using the Nmap -p option: Port list separated by commas: $ nmap -p80,443 localhost. Port range denoted with hyphens: $ nmap -p1-100 localhost. Alias for all ports from 1 to 65535: # nmap -p- localhost.
The Netstat command can list currently used ports, which might be helpful if you suspect an application is clashing with another one on an active port. Use the -an switch to show all connections and listening ports in numeric form.
Ports 0 through 1023 are defined as well-known ports. Registered ports are from 1024 to 49151. The remainder of the ports from 49152 to 65535 can be used dynamically by applications.
If you want to find a local open port to bind a server to, then you can create a ServerSocket
and if it does not throw an Exception, then it's open.
I did the following in one of my projects:
private int getAvailablePort() throws IOException {
int port = 0;
do {
port = RANDOM.get().nextInt(20000) + 10000;
} while (!isPortAvailable(port));
return port;
}
private boolean isPortAvailable(final int port) throws IOException {
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
return true;
} catch (final IOException e) {
} finally {
if (ss != null) {
ss.close();
}
}
return false;
}
RANDOM
is a ThreadLocal
here, but of course you can do an incrementing part there.
There's a little problem you may face in a multitasking windows/unix environment: if some isPortAvailable(final int port) from any of the answers returns a true for you, that doesn't mean, that at the moment when you will actually bind it it still will be available. The better solution would be create a method
ServerSocket tryBind(int portRangeBegin, int portRangeEnd) throws UnableToBindException;
So that you will just launch it and receive open socket for you, on some available port in the given range.
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