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

intfindFreePort(int startPort)
find Free Port
int current = startPort;
boolean found = false;
while (!found) {
    final Socket socket = new Socket();
    try {
        socket.connect(new InetSocketAddress("127.0.0.1", current), 100);
        current++;
    } catch (Exception ignored) {
...
intfindFreePort(int startPort)
Finds the next free port, starting with the one passed.
ServerSocket ss;
for (int i = startPort; i < 65536; i++) {
    try {
        ss = new ServerSocket(i);
    } catch (IOException e) {
        continue;
    ss.close();
...
intfindFreePortExcepting(int portToExclude)
Finds a free port on the machine, but allow the ability to specify a port number to not use, no matter what.
ServerSocket socket1 = null;
ServerSocket socket2 = null;
try {
    socket1 = new ServerSocket(0);
    socket2 = new ServerSocket(0);
    if (socket1.getLocalPort() != portToExclude) {
        return socket1.getLocalPort();
    return socket2.getLocalPort();
} finally {
    if (socket1 != null) {
        socket1.close();
    if (socket2 != null) {
        socket2.close();
intfindFreePortForApi()
find Free Port For Api
ServerSocket socket = null;
try {
    socket = new ServerSocket(0);
    return socket.getLocalPort();
} catch (IOException e) {
} finally {
    if (socket != null) {
        try {
...
intfindUnusedPort()
find Unused Port
try (final ServerSocket serverSocket = new ServerSocket(0)) {
    return serverSocket.getLocalPort();
} catch (IOException e) {
    throw new RuntimeException("Cannot find available port", e);
intfindUnusedPort()
find Unused Port
int port;
ServerSocket socket = new ServerSocket();
try {
    socket.bind(new InetSocketAddress(0));
    port = socket.getLocalPort();
} finally {
    socket.close();
return port;
intfindUnusedPort(int preferredPort)
Find and return an unused server socket port.
try {
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    ss.close();
    return port;
} catch (IOException ioe) {
return -1;
...
ListfindUnusedPorts(int numPorts)
Finds a number of unused TCP ports.
Closer closer = Closer.create();
List<Integer> freePorts = Lists.newArrayListWithCapacity(numPorts);
try {
    for (int i = 0; i < numPorts; i++) {
        try {
            ServerSocket serverSocket = new ServerSocket(0);
            closer.register(serverSocket);
            freePorts.add(serverSocket.getLocalPort());
...
intfreePort()
free Port
Random random = new Random();
int port;
do {
    port = random.nextInt(65535);
} while (isLocalPortUsing(port));
return port;
intfreePort()
free Port
ServerSocket ss = new ServerSocket(0);
try {
    return ss.getLocalPort();
} finally {
    ss.close();