Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i find an open ports in range of ports?

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.

like image 607
Erik Sapir Avatar asked Aug 22 '11 07:08

Erik Sapir


People also ask

How do I find open ports?

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.

How do I scan a range of ports in nmap?

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.

How do I see all the ports on my network?

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.

What is open port range?

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.


2 Answers

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.

like image 53
KARASZI István Avatar answered Sep 17 '22 15:09

KARASZI István


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.

like image 29
Illarion Kovalchuk Avatar answered Sep 21 '22 15:09

Illarion Kovalchuk