Here you can find the source of getFreePort()
public static int getFreePort()
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.io.IOException; import java.net.ServerSocket; public class Main { /**/*from www . j a va2s . co m*/ * Get available port. * * @return available port. -1 if no available ports exist */ public static int getFreePort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException ioe) { return -1; } } }