Here you can find the source of getRandomOpenPort()
public static int getRandomOpenPort() throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2016 Red Hat, Inc. //w w w . jav a 2s. c o m * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getRandomOpenPort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } } }