Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

get Available Port

License

Open Source License

Declaration

public static int getAvailablePort() 

Method Source Code


//package com.java2s;
import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    public static int getAvailablePort() {
        ServerSocket ss = null;/*from   w  w w .  j av a2 s  .c om*/
        try {
            ss = new ServerSocket();
            ss.bind(null);
            return ss.getLocalPort();
        } catch (IOException e) {
            throw new IllegalStateException("", e);
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static int getAvailablePort(int defaultPort) {
        int port = defaultPort;
        while (port < 65535) {
            if (!isPortInUse(port)) {
                return port;
            } else {
                port++;
            }
        }
        while (port > 0) {
            if (!isPortInUse(port)) {
                return port;
            } else {
                port--;
            }
        }
        throw new IllegalStateException("no available port");
    }

    public static boolean isPortInUse(int port) {
        boolean inUse = false;
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
            inUse = false;
        } catch (IOException e) {
            inUse = true;
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                }
            }
        }
        return inUse;
    }
}

Related

  1. getAvailablePort()
  2. getAvailablePort()
  3. getAvailablePort()
  4. getAvailablePort()
  5. getAvailablePort()
  6. getAvailablePort(final int basePort)
  7. getAvailablePort(int defaultPort)
  8. getAvailablePort(int port)
  9. getAvailablePort(int port)