Here you can find the source of getRandomPort()
public static int getRandomPort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getRandomPort() { try (ServerSocket s = new ServerSocket(0)) { return s.getLocalPort(); } catch (IOException e) { throw new RuntimeException("Can't get random port"); }/* ww w. j av a 2 s. c o m*/ } }