Java HTTP Port Find getFreePort()

Here you can find the source of getFreePort()

Description

Returns a free port number on localhost otherwise throws RuntimeException .

License

Open Source License

Return

a free port number on localhost

Declaration

public static int getFreePort() 

Method Source Code


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

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

public class Main {
    /**/* w  ww.  ja  va 2  s .c om*/
     * <p>Returns a free port number on localhost otherwise throws {@code RuntimeException}.</p>
     *
     * @return a free port number on localhost
     */
    public static int getFreePort() {
        try (ServerSocket serverSocket = new ServerSocket(0)) {
            serverSocket.setReuseAddress(true);
            return serverSocket.getLocalPort();
        } catch (IOException e) {
            throw new RuntimeException("Failed to get free port", e);
        }
    }
}

Related

  1. getEphemeralPort()
  2. getFreeLocalPort()
  3. getFreePort()
  4. getFreePort()
  5. getFreePort()
  6. getFreePort()
  7. getFreePort()
  8. getFreePort()
  9. getFreePort()