Here you can find the source of findFreePort()
public static int findFreePort()
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int findFreePort() { try {/*w w w.ja v a 2 s . co m*/ ServerSocket server = new ServerSocket(0); int port = server.getLocalPort(); server.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 0; } }