Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getAvailablePort() { ServerSocket ss = null;/*from w w w . j av a2 s .c om*/ try { ss = new ServerSocket(); ss.bind(null); return ss.getLocalPort(); } catch (IOException e) { throw new IllegalStateException("", e); } finally { if (ss != null) { try { ss.close(); } catch (IOException e) { } } } } public static int getAvailablePort(int defaultPort) { int port = defaultPort; while (port < 65535) { if (!isPortInUse(port)) { return port; } else { port++; } } while (port > 0) { if (!isPortInUse(port)) { return port; } else { port--; } } throw new IllegalStateException("no available port"); } public static boolean isPortInUse(int port) { boolean inUse = false; ServerSocket ss = null; try { ss = new ServerSocket(port); inUse = false; } catch (IOException e) { inUse = true; } finally { if (ss != null) { try { ss.close(); } catch (IOException e) { } } } return inUse; } }