Here you can find the source of getFreePort()
public static int getFreePort() throws Exception
//package com.java2s; import java.net.ServerSocket; public class Main { public static int getFreePort() throws Exception { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close();//from w w w .ja va 2s. c o m return port; } }