Here you can find the source of freePort()
public static int freePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int freePort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { }//w ww. j a v a2s . c o m throw new RuntimeException("could not find freeport on this host"); } }