Java HTTP Port Find findFreePort()

Here you can find the source of findFreePort()

Description

Returns a free TCP/IP port number on localhost.

License

Open Source License

Exception

Parameter Description
IllegalStateException if unable to find a free port

Return

a free TCP/IP port number on localhost

Declaration

public static int findFreePort() 

Method Source Code

//package com.java2s;
/**/*from   ww w. j  a  v a 2 s .  c  o m*/
 * Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import java.io.IOException;
import java.net.ServerSocket;

public class Main {
    /**
     * Returns a free TCP/IP port number on localhost.
     *
     * Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT just because of this).
     * Slightly improved with close() missing in JDT. And throws exception instead of returning -1.
     *
     * @return a free TCP/IP port number on localhost
     * @throws IllegalStateException if unable to find a free port
     */
    public static int findFreePort() {
        try (final ServerSocket socket = new ServerSocket(0)) {
            socket.setReuseAddress(true);
            return socket.getLocalPort();
        } catch (final IOException ex) {
            throw new IllegalStateException("Could not find a free TCP/IP port", ex);
        }
    }
}

Related

  1. findFreePort()
  2. findFreePort()
  3. findFreePort()
  4. findFreePort()
  5. findFreePort()
  6. findFreePort()
  7. findFreePort()
  8. findFreePort(int start, int len)
  9. findFreePort(int start, int limit)