Here you can find the source of findUnusedPort()
static int findUnusedPort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { static int findUnusedPort() { try (final ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } catch (IOException e) { throw new RuntimeException("Cannot find available port", e); }/*from w w w. ja v a2 s. c o m*/ } }