Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

Find a port that is available.

License

Apache License

Exception

Parameter Description
IllegalStateException if it cannot find an available port

Return

the number of the now-available port

Declaration

public static int getAvailablePort() 

Method Source Code

//package com.java2s;
/*/*  www.j  a  v a2  s.  c om*/
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 * 
 * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
 */

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**
     * Find a port that is available. This method starts a {@link ServerSocket} and obtains the port on which the socket is
     * listening, and then shuts down the socket so the port becomes available.
     * 
     * @return the number of the now-available port
     * @throws IllegalStateException if it cannot find an available port
     */
    public static int getAvailablePort() {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        } catch (IOException e) {
            throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e);
        }
    }
}

Related

  1. getAvailablePort()
  2. getAvailablePort()
  3. getAvailablePort()
  4. getAvailablePort()
  5. getAvailablePort()
  6. getAvailablePort()
  7. getAvailablePort()
  8. getAvailablePort()
  9. getAvailablePort()