Java HTTP Port Find getFreeLocalPort()

Here you can find the source of getFreeLocalPort()

Description

Return usable free local port

License

Open Source License

Exception

Parameter Description
IOException Exception may occur while trying to create the server socket

Return

port number

Declaration

public static int getFreeLocalPort() throws IOException 

Method Source Code

//package com.java2s;
/**/*from www  .  j a  va2s.co  m*/
Copyright KOMATSU Seiji (comutt), 2012, https://github.com/comutt/SimpleWebServer-mod
    
This software is modification of the original from http://www.jibble.org/miniwebserver/,
and licensed under the GNU General Public License (GPL) from the Free Software Foundation, http://www.fsf.org/.
    
Thanks to Paul James Mutton, the author of the original.
    
*/

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

public class Main {
    /**
     * Return usable free local port
     * @return port number
     * @throws IOException Exception may occur while trying to create the server socket
     */
    public static int getFreeLocalPort() throws IOException {
        final ServerSocket socket = new ServerSocket(0);
        try {
            return socket.getLocalPort();
        } finally {
            socket.close();
        }
    }
}

Related

  1. getAvailablePortsFromRange(int portMin, int portMax, int numberOfPorts)
  2. getAvialablePort(final int basePort)
  3. getCorrectHostnamePort(String hostPort)
  4. getEffectivePort(String scheme, int specifiedPort)
  5. getEphemeralPort()
  6. getFreePort()
  7. getFreePort()
  8. getFreePort()
  9. getFreePort()