Java HTTP Port Find getPort(final int suggestedPort)

Here you can find the source of getPort(final int suggestedPort)

Description

Return an open port on current machine.

License

Open Source License

Declaration

protected static int getPort(final int suggestedPort)
        throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.net.BindException;

import java.net.ServerSocket;

public class Main {
    /**/* w w  w .  java2s  . c  o  m*/
     * Return an open port on current machine. Try the suggested port first. If
     * suggestedPort is zero, just select a random port
     */
    protected static int getPort(final int suggestedPort)
            throws IOException {

        ServerSocket openSocket;

        try {

            openSocket = new ServerSocket(suggestedPort);

        } catch (BindException ex) {

            // the port is busy, so look for a random open port
            openSocket = new ServerSocket(0);

        }

        final int port = openSocket.getLocalPort();

        openSocket.close();

        return port;

    }
}

Related

  1. getNextAvailablePort(final int min, final int max, final Collection excepted)
  2. getNextAvailablePort(int port)
  3. getNodeName(final String managementServerHostName, final int managementPort)
  4. getNonPrivilegedPort()
  5. getOpenPort()
  6. getPort(int port)
  7. getPort(Proxy proxy)
  8. getPort(String endpoint)
  9. getPort(String hostAndPort)