Java HTTP Port Find findFreePort()

Here you can find the source of findFreePort()

Description

See https://gist.github.com/vorburger/3429822 Returns a free port number on localhost.

License

Open Source License

Exception

Parameter Description
IllegalStateException if unable to find a free port

Return

a free port number on localhost

Declaration

public static int findFreePort() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /** See https://gist.github.com/vorburger/3429822
     * Returns a free port number on localhost.
     *//from w  w w.  j a  va 2 s . c  om
     * 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 port number on localhost
     * @throws IllegalStateException if unable to find a free port
     */
    public static int findFreePort() {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);
            socket.setReuseAddress(true);
            int port = socket.getLocalPort();
            try {
                socket.close();
            } catch (IOException e) {
                // Ignore IOException on close()
            }
            return port;
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
        throw new IllegalStateException("Could not find a free TCP/IP port");
    }
}

Related

  1. findAvailablePort(String hostname, int startPort, int endPort)
  2. findAvailablePorts(int n)
  3. findFreePort()
  4. findFreePort()
  5. findFreePort()
  6. findFreePort()
  7. findFreePort()
  8. findFreePort()
  9. findFreePort()