Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getAvailablePort() { try {// w w w .j a v a2 s.co m ServerSocket socket = new ServerSocket(0); try { return socket.getLocalPort(); } finally { socket.close(); } } catch (IOException e) { throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e); } } }