Here you can find the source of getFreePort()
public static int getFreePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getFreePort() { try {/*from www. j a v a 2 s . co m*/ try (ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); return socket.getLocalPort(); } } catch (IOException e) { return -1; } } }