Here you can find the source of getRandomPort()
private static int getRandomPort() throws IOException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.*; public class Main { private static int getRandomPort() throws IOException { for (int port = 22332; port < 22500; port++) { if (trySocket(port)) { return port; }//from w w w. j a v a 2 s . c o m } throw new IllegalStateException("Cannot find a single free port"); } private static boolean trySocket(int port) throws IOException { InetAddress address = Inet4Address.getByName("localhost"); ServerSocket s = null; try { s = new ServerSocket(); s.bind(new InetSocketAddress(address, port)); return true; } catch (IOException exp) { System.err.println("Port " + port + " already in use, tying next ..."); // exp.printStackTrace(); // next try .... } finally { if (s != null) { s.close(); } } return false; } }