Java HTTP Port Find getRandomFreePort()

Here you can find the source of getRandomFreePort()

Description

get Random Free Port

License

Apache License

Declaration

public static int getRandomFreePort() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import java.util.Random;

public class Main {
    private final static Random random = new Random();
    private final static int MAX_PORT = 65535;
    private final static int MIN_PORT = MAX_PORT / 2;

    public static int getRandomFreePort() {
        return getRandomFreePort(MIN_PORT, MAX_PORT);
    }//ww  w .ja  v a 2 s .  co m

    public static int getRandomFreePort(int minPort, int maxPort) {
        int port = 0;
        boolean found = false;
        do {
            port = getRandomPortNumber(minPort, maxPort);
            found = isPortFree(port);
        } while (!found);
        return port;
    }

    private static int getRandomPortNumber(int minPort, int maxPort) {
        if (maxPort < minPort) {
            throw new IllegalArgumentException();
        }
        return random.nextInt(maxPort - minPort) + minPort;
    }

    public static boolean isPortFree(int port) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                }
            }
        }
        return false;
    }
}

Related

  1. getPortInRange(int minPort, int maxPort)
  2. getPorts(int count)
  3. getPorts(int number, int MIN_PORT_NUMBER, int MAX_PORT_NUMBER)
  4. getPrometheusMetrics(int metricsPort)
  5. getRandomAvailablePort()
  6. getRandomFreePort()
  7. getRandomOpenPort()
  8. getRandomPort()
  9. getRandomPort()