Here you can find the source of findFreePort()
public static int findFreePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int findFreePort() { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } catch (IOException e) { throw new RuntimeException(e); }/*from w w w.j a v a 2 s.com*/ } }