Java HTTP Port Find findAvailablePort(int port)

Here you can find the source of findAvailablePort(int port)

Description

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

License

LGPL

Parameter

Parameter Description
port The specified port.

Return

The first available port.

Declaration


public static int findAvailablePort(int port) 

Method Source Code

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

import java.net.Socket;

public class Main {
    /**//  w w w  .  j  a  v  a2 s . co m
    * <p>Determines the first available port, beginning at the specified
    * port.  The search is abandoned after 500 increments.</p>
    * @param port The specified port.
    * @return The first available port.
    */

    public static int findAvailablePort(int port) {
        int limit = 500;
        Socket socket;
        while (limit > 0) {
            try {
                socket = new Socket("localhost", port);
                socket.close();
                limit--;
                port++;
                continue;
            } catch (Exception e) {
                //        e.printStackTrace();
                return port;
            }
        }
        return -1;
    }
}

Related

  1. findAvailablePort()
  2. findAvailablePort()
  3. findAvailablePort(int min, int max)
  4. findAvailablePort(int minPort, int maxPort)
  5. findAvailablePort(int port)
  6. findAvailablePort(String hostname, int startPort, int endPort)
  7. findAvailablePorts(int n)
  8. findFreePort()
  9. findFreePort()