Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

Returns port number which is currently not listened by local services.

License

Apache License

Return

port number

Declaration

public static int getAvailablePort() 

Method Source Code


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

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**/*ww  w . j  av a2 s  .  co  m*/
     * Returns port number which is currently not listened by local services.
     *
     * @return port number
     */
    public static int getAvailablePort() {
        try (final ServerSocket ss = new ServerSocket(0)) {
            return ss.getLocalPort();
        } catch (final IOException e) {
            throw new IllegalStateException("Unable to get local port: no ports available");
        }
    }
}

Related

  1. getAvailablePort()
  2. getAvailablePort()
  3. getAvailablePort()
  4. getAvailablePort()
  5. getAvailablePort()
  6. getAvailablePort()
  7. getAvailablePort()
  8. getAvailablePort()
  9. getAvailablePort()