Class AvailablePortFinder


  • public final class AvailablePortFinder
    extends Object
    Finds currently available server ports.
    • Method Detail

      • getNextAvailable

        public static int getNextAvailable()
        Gets the next available port.
        Returns:
        the available port
        Throws:
        IllegalStateException - if there are no ports available
      • getNextAvailable

        public static int getNextAvailable​(int fromPort,
                                           int toPort)
        Gets the next available port in the given range.
        Parameters:
        fromPort - port number start range.
        toPort - port number end range.
        Returns:
        the available port
        Throws:
        IllegalStateException - if there are no ports available
      • getSpecificPort

        public static <T> int getSpecificPort​(int portNumber,
                                              T failurePayload,
                                              Function<T,​Integer> failureHandler)
        Gets the next available port in the given range.
        Parameters:
        portNumber - port number start range.
        failurePayload - handover data in case port allocation fails (i.e.: a default one to use)
        failureHandler - a handler in case the requested port is not available
        Returns:
        the available port
        Throws:
        IllegalStateException - if there are no ports available
      • probePort

        public static int probePort​(int port)
        Probe a port to see if it is free
        Parameters:
        port - an integer port number to be tested. If port is 0, then the next available port is returned.
        Returns:
        the port number itself if the port is free or, in case of port 0, the first available port number.
        Throws:
        IllegalStateException - if the port is not free or, in case of port 0, if there are no ports available at all.
      • probePort

        public static int probePort​(InetAddress address,
                                    int port)
        Probe a port to see if it is free
        Parameters:
        port - an integer port number to be tested. If port is 0, then the next available port is returned.
        Returns:
        the port number itself if the port is free or, in case of port 0, the first available port number.
        Throws:
        IllegalStateException - if the port is not free or, in case of port 0, if there are no ports available at all.