Here you can find the source of freePort()
public static int freePort() throws IOException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int freePort() throws IOException { ServerSocket ss = new ServerSocket(0); try {//from w w w . j a v a 2 s .c o m return ss.getLocalPort(); } finally { ss.close(); } } }