Java tutorial
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int findFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } } }