OneCompiler

Finding Available Port in System using Java

473

SpringBoot allows you to start your application on any available port on the running computer. This is helpful especially when your service/ application does not expose any UI/ API and just perform some backend activities. Another advantage is you can run more than one process on the same computer.

Following id the configuration we need to add to application.properties to make SpringBoot choose the available port

server.port=0

And following is the Java equivalent code to find and return an available port from the System.

import java.io.IOException;
import java.net.ServerSocket;

public class FindAvailablePort {
  
    public static final int findAvailablePort(int min, int max) {
        for (int port = min; port < max; port++) {
            try {
                new ServerSocket(port).close();
                return port;
            } catch (IOException e) {
                // Ignore, already be taken
            }
        }
        throw new IllegalStateException("No port available in range " + min + " to " + max);
     }
  
    public static void main(String[] args) {
       System.out.println(findAvailablePort(1000, 5000));
    }
}

You can try executing this program here https://onecompiler.com/java/3v6nn7g6k