Java HTTP Port Find findFreePort(int startPort)

Here you can find the source of findFreePort(int startPort)

Description

Finds the next free port, starting with the one passed.

License

Apache License

Parameter

Parameter Description
startPort First port to be probed.

Exception

Parameter Description
IOException IOE is thrown if we can't close a socket we tried to open or if we runout of ports to try.

Return

A currently usable port.

Declaration

public static int findFreePort(int startPort) throws IOException 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**/*from   w w w  . j  a  v  a  2 s.  c om*/
     * Finds the next free port, starting with the one passed. Keep in mind the
     * time-of-check-time-of-use nature of this method, the returned port might become occupied
     * after it was checked for availability.
     * @param startPort First port to be probed.
     * @return A currently usable port.
     * @throws IOException IOE is thrown if we can't close a socket we tried to open or if we run
     * out of ports to try.
     */
    public static int findFreePort(int startPort) throws IOException {
        ServerSocket ss;
        for (int i = startPort; i < 65536; i++) {
            try {
                ss = new ServerSocket(i);
            } catch (IOException e) {
                continue;
            }
            ss.close();
            return i;
        }
        throw new IOException("Ran out of ports.");
    }
}

Related

  1. findFreePort()
  2. findFreePort()
  3. findFreePort(int start, int len)
  4. findFreePort(int start, int limit)
  5. findFreePort(int startPort)
  6. findFreePortExcepting(int portToExclude)
  7. findFreePortForApi()
  8. findUnusedPort()
  9. findUnusedPort()