Here you can find the source of getFreePort()
Returns a free port number on localhost otherwise throws RuntimeException .
public static int getFreePort()
//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); } } }