Here you can find the source of findAvailablePort()
public static int findAvailablePort()
//package com.java2s; /*//from w w w .j a v a 2 s. co m * Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, without warranties or * conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the * specific language governing permissions and limitations under the License. */ import java.io.IOException; import java.net.ServerSocket; import java.util.logging.Logger; public class Main { /** * Requests a random server socket port to be created, closes it, and returns the port picked * as a potentially available port. Note, that this is not an atomic probe and acquire, so the port * might be taken by the time a bind occurs. */ public static int findAvailablePort() { int port = 0; ServerSocket socket = null; try { socket = new ServerSocket(0); socket.setReuseAddress(true); port = socket.getLocalPort(); Logger.getAnonymousLogger().info("port candidate:" + port); } catch (Throwable e) { Logger.getAnonymousLogger().severe(e.toString()); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } return port; } }