Java Utililty Methods HTTP Port Find

List of utility methods to do HTTP Port Find

Description

The list of methods to do HTTP Port Find are organized into topic(s).

Method

intfindAvailablePort()
Finds the first available TCP server port.
ServerSocket serverSocket = null;
try {
    serverSocket = new ServerSocket(0);
    return serverSocket.getLocalPort();
} finally {
    if (serverSocket != null) {
        serverSocket.close();
intfindAvailablePort(int min, int max)
find Available Port
for (int port = min; port < max; port++) {
    try {
        new ServerSocket(port).close();
        return port;
    } catch (IOException e) {
throw new IllegalStateException("Could not find available port in range " + min + " to " + max);
...
ServerSocketfindAvailablePort(int minPort, int maxPort)
find Available Port
synchronized (lock) {
    for (int i = minPort; i < maxPort; i++) {
        try {
            return new ServerSocket(i);
        } catch (IOException ex) {
throw new IOException("no available port found");
intfindAvailablePort(int port)
Creates a server socket, bound to the specified port.
try (ServerSocket s = new ServerSocket(port)) {
    return s.getLocalPort();
} catch (IOException e) {
    throw e;
intfindAvailablePort(int port)

Determines the first available port, beginning at the specified port.

int limit = 500;
Socket socket;
while (limit > 0) {
    try {
        socket = new Socket("localhost", port);
        socket.close();
        limit--;
        port++;
...
intfindAvailablePort(String hostname, int startPort, int endPort)
Finds an available port within a port range on a host
for (int port = startPort; port < (endPort + 1); port++) {
    try {
        Socket socket = new Socket(InetAddress.getByName(hostname), port);
        socket.close();
    } catch (IOException e) {
        return port;
return 0;
int[]findAvailablePorts(int n)
find Available Ports
int ports[] = new int[n];
ServerSocket[] sockets = new ServerSocket[n];
for (int i = 0; i < n; i++) {
    ServerSocket s = new ServerSocket(0);
    s.setReuseAddress(true);
    ports[i] = s.getLocalPort();
    sockets[i] = s;
for (int i = 0; i < n; i++)
    sockets[i].close();
return ports;
intfindFreePort()
find Free Port
try (ServerSocket serverSocket = new ServerSocket(0)) {
    return serverSocket.getLocalPort();
} catch (IOException e) {
    throw new RuntimeException(e);
intfindFreePort()
find Free Port
try {
    ServerSocket server = new ServerSocket(0);
    int port = server.getLocalPort();
    server.close();
    return port;
} catch (IOException e) {
    e.printStackTrace();
return 0;
intfindFreePort()
find Free Port
try (ServerSocket socket = new ServerSocket(0)) {
    return socket.getLocalPort();