Here you can find the source of getRandomFreePort()
public static int getRandomFreePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; import java.util.Random; public class Main { private final static Random random = new Random(); private final static int MAX_PORT = 65535; private final static int MIN_PORT = MAX_PORT / 2; public static int getRandomFreePort() { return getRandomFreePort(MIN_PORT, MAX_PORT); }//ww w .ja v a 2 s . co m public static int getRandomFreePort(int minPort, int maxPort) { int port = 0; boolean found = false; do { port = getRandomPortNumber(minPort, maxPort); found = isPortFree(port); } while (!found); return port; } private static int getRandomPortNumber(int minPort, int maxPort) { if (maxPort < minPort) { throw new IllegalArgumentException(); } return random.nextInt(maxPort - minPort) + minPort; } public static boolean isPortFree(int port) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); serverSocket.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException ex) { } } } return false; } }