Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.net.ServerSocket; public class Main { /**//from w ww .j a v a 2 s .com * @return Port, available for local use */ public static int getAvailablePort() { try { try (final ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } } catch (IOException e) { throw new IllegalStateException(e); } } }