Here you can find the source of getFreePort()
public static int getFreePort()
//package com.java2s; //License from project: Apache License import java.net.ServerSocket; public class Main { public static int getFreePort() { try {//from ww w . ja v a 2 s . c om final ServerSocket ss = new ServerSocket(0); ss.setReuseAddress(true); final int port = ss.getLocalPort(); ss.close(); return port; } catch (final Throwable t) { throw new RuntimeException(t); } } }