Java HTTP Port Find getUnusedPort(int startPort)

Here you can find the source of getUnusedPort(int startPort)

Description

Returns an unused port number on the local host.

License

LGPL

Parameter

Parameter Description
startPort suggested port number; ports nearby will be chosen if this is in use

Declaration

static int getUnusedPort(int startPort) throws IOException 

Method Source Code

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

import java.io.IOException;

import java.net.ConnectException;

import java.net.Socket;

public class Main {
    /**/*from   w w w .j  ava 2s.  c o m*/
     * True if spurious java.util.NoSuchElementExceptions should be flagged.
     * If future JVMs fix this bug, this should be set false or the code
     * removed.
     */
    public static boolean WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS = true;

    /**
     * Returns an unused port number on the local host.
     *
     * @param   startPort  suggested port number; ports nearby will be
     *          chosen if this is in use
     */
    static int getUnusedPort(int startPort) throws IOException {
        final int nTry = 20;
        for (int iPort = startPort; iPort < startPort + nTry; iPort++) {
            try {
                Socket trySocket = new Socket("localhost", iPort);
                if (!trySocket.isClosed()) {

                    /* This line causes "java.util.NoSuchElementException" to
                     * be written to System.err, at least at J2SE1.4.
                     * Not my fault! */
                    if (WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS) {
                        WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS = false;
                        System.err.println(
                                "Please ignore spurious \"" + "java.util.NoSuchElementException\" messages.");
                    }
                    trySocket.close();
                }
            } catch (ConnectException e) {

                /* Can't connect - this hopefully means that the socket is
                 * unused. */
                return iPort;
            }
        }
        throw new IOException("Can't locate an unused port in range " + startPort + " ... " + (startPort + nTry));
    }
}

Related

  1. getServerPort()
  2. getSupportedConnectionTypes(Map map)
  3. getSupportedEntityTypes()
  4. getUnusedPort()
  5. getUnusedPort(final int start)
  6. getUnusedPorts(final int count, final int start)
  7. getValidZooKeeperPort()
  8. getWsdlLocation(String portPrefix)
  9. getXmlReport(String fileName)