Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

get Available Port

License

Apache License

Declaration

public static int getAvailablePort() 

Method Source Code


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

import java.io.IOException;
import java.net.*;

import java.util.Random;

public class Main {
    private static final int RND_PORT_START = 30000;
    private static final int RND_PORT_RANGE = 10000;
    private static final Random RANDOM = new Random(System.currentTimeMillis());
    private static final int MAX_PORT = 65535;

    public static int getAvailablePort() {
        ServerSocket ss = null;/*from  w ww . jav  a 2 s  .  c  om*/
        try {
            ss = new ServerSocket();
            ss.bind(null);
            return ss.getLocalPort();
        } catch (IOException e) {
            return getRandomPort();
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static int getAvailablePort(int port) {
        if (port <= 0) {
            return getAvailablePort();
        }
        for (int i = port; i < MAX_PORT; i++) {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(i);
                return i;
            } catch (IOException e) {
                // continue
            } finally {
                if (ss != null) {
                    try {
                        ss.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        return port;
    }

    public static int getRandomPort() {
        return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE);
    }
}

Related

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