Java HTTP Port Find findAvailablePort(String hostname, int startPort, int endPort)

Here you can find the source of findAvailablePort(String hostname, int startPort, int endPort)

Description

Finds an available port within a port range on a host

License

LGPL

Parameter

Parameter Description
hostname Host name
startPort Port number starting the range
endPort Port number ending the range

Return

An available port number, or 0 if none is available.

Declaration

public static synchronized int findAvailablePort(String hostname, int startPort, int endPort) 

Method Source Code


//package com.java2s;
/*/* w  ww.  jav  a2  s  .  c om*/
 * Ghost4J: a Java wrapper for Ghostscript API.
 *
 * Distributable under LGPL license.
 * See terms of license at http://www.gnu.org/licenses/lgpl.html.
 */

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class Main {
    /**
     * Finds an available port within a port range on a host
     * 
     * @param hostname
     *            Host name
     * @param startPort
     *            Port number starting the range
     * @param endPort
     *            Port number ending the range
     * @return An available port number, or 0 if none is available.
     */
    public static synchronized int findAvailablePort(String hostname, int startPort, int endPort) {

        for (int port = startPort; port < (endPort + 1); port++) {

            try {
                Socket socket = new Socket(InetAddress.getByName(hostname), port);
                // port not available
                socket.close();
            } catch (IOException e) {
                // port available
                return port;
            }
        }

        return 0;
    }
}

Related

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