Here you can find the source of findFreePortForApi()
public static int findFreePortForApi()
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int findFreePortForApi() { ServerSocket socket = null; try {// ww w .j a v a2 s .c o m socket = new ServerSocket(0); return socket.getLocalPort(); } catch (IOException e) { } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return -1; } }