Java HTTP Port Find findFreePort()

Here you can find the source of findFreePort()

Description

This is really only used for unit tests but is included in the library so it can be reused across modules.

License

Apache License

Declaration

public static int findFreePort() 

Method Source Code


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

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static List<Integer> ourPorts = new ArrayList<Integer>();

    /**//from www .j a v  a 2s .  c  o m
     * This is really only used for unit tests but is included in the library so it can be reused across modules. Use with caution.
     */
    public static int findFreePort() {
        ServerSocket server;
        try {
            server = new ServerSocket(0);
            int port = server.getLocalPort();
            ourPorts.add(port);
            server.close();
            Thread.sleep(500);
            return port;
        } catch (IOException e) {
            throw new Error(e);
        } catch (InterruptedException e) {
            throw new Error(e);
        }
    }
}

Related

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