[java] How to find an available port?

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.

  1. In which range of port numbers should I search for? (I used ports 12345, 12346, and 12347 and it was fine).

  2. How can I find out if a given port is not occupied by another software?

This question is related to java networking sockets port

The answer is


If your server starts up, then that socket was not used.

EDIT

Something like:

ServerSocket s = null ;

try { 
    s = new ServerSocket( 0 ); 
} catch( IOException ioe ){
   for( int i = START; i < END ; i++ ) try {
        s = new ServerSocket( i );
    } catch( IOException ioe ){}
}
// At this point if s is null we are helpless
if( s == null ) {
    throw new IOException(
       Strings.format("Unable to open server in port range(%d-%d)",START,END));
}

See ServerSocket:

Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.


This works for me on Java 6

    ServerSocket serverSocket = new ServerSocket(0);
    System.out.println("listening on port " + serverSocket.getLocalPort());

It may not help you much, but on my (Ubuntu) machine I have a file /etc/services in which at least the ports used/reserved by some of the apps are given. These are the standard ports for those apps.

No guarantees that these are running, just the default ports these apps use (so you should not use them if possible).

There are slightly more than 500 ports defined, about half UDP and half TCP.

The files are made using information by IANA, see IANA Assigned port numbers.


If you want to create your own server using a ServerSocket, you can just have it pick a free port for you:

  ServerSocket serverSocket = new ServerSocket(0);
  int port = serverSocket.getLocalPort();

Other server implementations typically have similar support. Jetty for example picks a free port unless you explicitly set it:

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  // don't call: connector.setPort(port);
  server.addConnector(connector);
  server.start();
  int port = connector.getLocalPort();

Starting from Java 1.7 you can use try-with-resources like this:

  private Integer findRandomOpenPortOnAllLocalInterfaces() throws IOException {
    try (
        ServerSocket socket = new ServerSocket(0);
    ) {
      return socket.getLocalPort();

    }
  }

If you need to find an open port on a specific interface check ServerSocket documentation for alternative constructors.

Warning: Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance.


Using 'ServerSocket' class we can identify whether given port is in use or free. ServerSocket provides a constructor that take an integer (which is port number) as argument and initialise server socket on the port. If ServerSocket throws any IO Exception, then we can assume this port is already in use.

Following snippet is used to get all available ports.

for (int port = 1; port < 65535; port++) {
         try {
                  ServerSocket socket = new ServerSocket(port);
                  socket.close();
                  availablePorts.add(port);
         } catch (IOException e) {

         }
}

Reference link.


If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.


I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:

<dependency>
    <groupId>me.alexpanov</groupId>
    <artifactId>free-port-finder</artifactId>
    <version>1.0</version>
</dependency>

Once installed, free port numbers can be obtained via:

int port = FreePortFinder.findFreeLocalPort();

The Eclipse SDK contains a class SocketUtil, that does what you want. You may have a look into the git source code.


If you need in range use:

public int nextFreePort(int from, int to) {
    int port = randPort(from, to);
    while (true) {
        if (isLocalPortFree(port)) {
            return port;
        } else {
            port = ThreadLocalRandom.current().nextInt(from, to);
        }
    }
}

private boolean isLocalPortFree(int port) {
    try {
        new ServerSocket(port).close();
        return true;
    } catch (IOException e) {
        return false;
    }
}


According to Wikipedia, you should use ports 49152 to 65535 if you don't need a 'well known' port.

AFAIK the only way to determine wheter a port is in use is to try to open it.


If you are using the Spring Framework, the most straightforward way to do this is:

private Integer laancNotifyPort = SocketUtils.findAvailableTcpPort();

You can also set an acceptable range, and it will search in this range:

private Integer laancNotifyPort = SocketUtils.findAvailableTcpPort(9090, 10090);

This is a convenience method that abstracts away the complexity but internally is similar to a lot of the other answers on this thread.


If you are using Spring, the answer provided by Michail Nikolaev is the simplest and cleanest one, and IMO should be upvoted. Just for convenience purposes, I'll add an inline example using the Springframwework SocketUtils.findAvailableTcpPort() method:

int randomAvailablePort = SocketUtils.findAvailableTcpPort();

It's as easy as that, just one line :). Of course, the Utils class offer many other interesting methods, I suggest having a look at the docs.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to networking

Access HTTP response as string in Go Communication between multiple docker-compose projects Can't access 127.0.0.1 How do I delete virtual interface in Linux? ConnectivityManager getNetworkInfo(int) deprecated Bridged networking not working in Virtualbox under Windows 10 Difference between PACKETS and FRAMES How to communicate between Docker containers via "hostname" java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused) wget: unable to resolve host address `http'

Examples related to sockets

JS file gets a net::ERR_ABORTED 404 (Not Found) mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 TypeError: a bytes-like object is required, not 'str' Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED No connection could be made because the target machine actively refused it 127.0.0.1 Sending a file over TCP sockets in Python socket connect() vs bind() java.net.SocketException: Connection reset by peer: socket write error When serving a file How do I use setsockopt(SO_REUSEADDR)?

Examples related to port

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated How do I kill the process currently using a port on localhost in Windows? Node.js Port 3000 already in use but it actually isn't? Can't connect to Postgresql on port 5432 Spring Boot - How to get the running port Make docker use IPv4 for port binding How to change the default port of mysql from 3306 to 3360 Open firewall port on CentOS 7 Unable to launch the IIS Express Web server, Failed to register URL, Access is denied XAMPP Port 80 in use by "Unable to open process" with PID 4