Java HTTP Port Find getFreePort()

Here you can find the source of getFreePort()

Description

tries to get a free port and returns it

License

Apache License

Return

the free port , -1 if no port

Declaration

public static int getFreePort() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    /**// w  w w.java2s  . co  m
     * tries to get a free port and returns it
     * @return the free port , -1 if no port
     */
    public static int getFreePort() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(0);
            int freePort = serverSocket.getLocalPort();

            return freePort;
        } catch (IOException e) {
            return -1;
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                //do nothing
            }
        }

    }
}

Related

  1. getFreePort()
  2. getFreePort()
  3. getFreePort()
  4. getFreePort()
  5. getFreePort()
  6. getFreePort()
  7. getFreePort()
  8. getFreePort()
  9. getFreePort(int port)