Here you can find the source of getAvailablePort()
Parameter | Description |
---|---|
IllegalStateException | if it cannot find an available port |
public static int getAvailablePort()
//package com.java2s; /*/* www.j a v a2 s. c om*/ * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ import java.io.IOException; import java.net.ServerSocket; public class Main { /** * Find a port that is available. This method starts a {@link ServerSocket} and obtains the port on which the socket is * listening, and then shuts down the socket so the port becomes available. * * @return the number of the now-available port * @throws IllegalStateException if it cannot find an available port */ public static int getAvailablePort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e); } } }