Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { /**/*ww w . j av a2 s . co m*/ * Returns port number which is currently not listened by local services. * * @return port number */ public static int getAvailablePort() { try (final ServerSocket ss = new ServerSocket(0)) { return ss.getLocalPort(); } catch (final IOException e) { throw new IllegalStateException("Unable to get local port: no ports available"); } } }