Here you can find the source of getAvailablePort(int defaultPort)
public static int getAvailablePort(int defaultPort) throws IOException
//package com.java2s; import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getAvailablePort(int defaultPort) throws IOException { try {//from ww w .j a v a 2 s .com ServerSocket ss = new ServerSocket(defaultPort); ss.close(); return defaultPort; } catch (IOException e) { } ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); ss.close(); return port; } }