Here you can find the source of findFreePort()
public static int findFreePort() throws Exception
//package com.java2s; import java.net.ServerSocket; public class Main { public static int findFreePort() throws Exception { int port; ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort();//from w ww. j a v a 2s . co m socket.close(); return port; } }