Java HTTP Port Find findAvailablePort(int minPort, int maxPort)

Here you can find the source of findAvailablePort(int minPort, int maxPort)

Description

find Available Port

License

Apache License

Declaration

public static ServerSocket findAvailablePort(int minPort, int maxPort) throws IOException 

Method Source Code


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

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

public class Main {
    private static final Object lock = new Object();

    public static ServerSocket findAvailablePort(int minPort, int maxPort) throws IOException {
        synchronized (lock) {
            for (int i = minPort; i < maxPort; i++) {
                try {
                    return new ServerSocket(i);
                } catch (IOException ex) {
                    // try next port
                }/*from   w ww . j  av a 2 s .c  om*/
            }
        }

        // if the program gets here, no port in the range was found
        throw new IOException("no available port found");
    }
}

Related

  1. exportResource(Class fromClass, String resourceName, String exportPath)
  2. findAvailablePort()
  3. findAvailablePort()
  4. findAvailablePort()
  5. findAvailablePort(int min, int max)
  6. findAvailablePort(int port)
  7. findAvailablePort(int port)
  8. findAvailablePort(String hostname, int startPort, int endPort)
  9. findAvailablePorts(int n)