Here you can find the source of findAvailablePort()
public static int findAvailablePort()
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int findAvailablePort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { throw new RuntimeException(e); }//w w w . j a va2s.co m } }