1

我正在为我们的组织开发 eclipse 插件。我们通过 eclipse 使用这个插件在用户机器上打开多个服务器[最少 10 个服务器]。对于启动服务器,我们需要尚未绑定的端口号。为此,我使用 serversocket 来检查这一点。我认为打开 serversocket 对象是一项昂贵的操作。在内部 serversocket 将检查端口是否已绑定它至少需要 50 毫秒。这是我返回自由端口的代码。有没有办法在不使用操作系统命令和打开 ServerSocket 的情况下找到已经占用的端口?

     /**
     *Tries 100 times
     * @param port
     * modes
     *  1.increment - 1
     *  This mode increment the port with your start value . But it's costly operation because each time we open a socket and check the port is free .
     *  2.decrement - 2
     *  Invert of increment.
     *  3.random - 3
     *  Randomly choose based on your starting point
     * @return
     */
    public static String getDefaultPort(int port , int mode){
        int retry = 100;
        int random = 3;
        int increment = 1;
        int decrement = 2;
        while(true){
            //this is for preventing stack overflow error.
            if(retry < 1){ //retries 100 times .
                break;
            }
            if(mode==increment){
                port++;
            }else if(mode == decrement){
                port--;
            }else if(mode == random){
                port = (int) (port+Math.floor((Math.random()*1000)));
            }
            if(validate(port+"")){
                long end = System.currentTimeMillis();
                return port+"";
            }
        }
        return "";
    }

    public boolean validate(String input) {
    boolean status = true;
    try {
        int port = Integer.parseInt(input);
        ServerSocket ss = new ServerSocket(port);
        ss.close();         
    }
    catch (Exception e) {
        status = false;
    }
    return status;
}
4

1 回答 1

2

最快的方法是运行本机netstat命令并解析输出。它也可以在 Windows 和 Linux 平台上使用。一个典型的 netstat 命令输出如下

 Proto  Local Address          Foreign Address        State
 TCP    MYHOST:8080           MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:9090           MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:3389           MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:7717           MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:51114          MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:netbios-ssn    MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:netbios-ssn    MYHOST.mydomain.co.in:0  LISTENING
 TCP    MYHOST:2573           hj-lyncfe.mydomain.co.in:5061  ESTABLISHED
 TCP    MYHOST:2591           mail.mydomain.co.in:8502  ESTABLISHED
 TCP    MYHOST:2593           mail.mydomain.co.in:8502  ESTABLISHED

您感兴趣的端口在Local Address带有in 的列StateLISTENING

于 2012-07-05T09:59:04.167 回答