Java HTTP Port Find findAvailablePort(int port)

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

Description

Creates a server socket, bound to the specified port.

License

Apache License

Exception

Parameter Description
IOException an exception

Declaration

public static int findAvailablePort(int port) throws IOException 

Method Source Code


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

import java.io.IOException;
import java.net.ServerSocket;

public class Main {
    /** //  w ww . j a v a 2s  . co m
     *  Creates a server socket, bound to the specified port.
     *  A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range.
     *  This port number can then be retrieved by calling getLocalPort.
     * 
     * @return
     * @throws IOException
     */
    public static int findAvailablePort(int port) throws IOException {
        try (ServerSocket s = new ServerSocket(port)) {
            return s.getLocalPort();
        } catch (IOException e) {
            throw e;
        }
    }
}

Related

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