测试远程端口是否正在使用中

Jef*_*man 8 java sockets

我需要发现远程服务器上的开放端口.我想知道这是否可行.我在想我打开一个套接字,如果这个成功,就意味着它被使用了......否则,如果我得到一个异常,那么就不会使用它.

例如,

public boolean isActive() {
    Socket s = null;
    try {
        s = new Socket();
        s.setReuseAddress(true);
        SocketAddress sa = new InetSocketAddress(this.host, this.port);
        s.connect(sa, 3000);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这是一种可行的方法吗?

Ala*_*ier 14

FWIW,我经常使用的Java解决方案(优于telnet:支持超时).

package com.acme.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class CheckSocket {

    public static void main(String[] args) {
        int exitStatus = 1 ;
        if (args.length != 3) {
            System.out.println("Usage: CheckSocket node port timeout");
        } else {
            String node = args[0];
            int port = Integer.parseInt(args[1]);
            int timeout = Integer.parseInt(args[2]);

            Socket s = null;
            String reason = null ;
            try {
                s = new Socket();
                s.setReuseAddress(true);
                SocketAddress sa = new InetSocketAddress(node, port);
                s.connect(sa, timeout * 1000);
            } catch (IOException e) {
                if ( e.getMessage().equals("Connection refused")) {
                    reason = "port " + port + " on " + node + " is closed.";
                };
                if ( e instanceof UnknownHostException ) {
                    reason = "node " + node + " is unresolved.";
                }
                if ( e instanceof SocketTimeoutException ) {
                    reason = "timeout while attempting to reach node " + node + " on port " + port;
                }
            } finally {
                if (s != null) {
                    if ( s.isConnected()) {
                        System.out.println("Port " + port + " on " + node + " is reachable!");
                        exitStatus = 0;
                    } else {
                        System.out.println("Port " + port + " on " + node + " is not reachable; reason: " + reason );
                    }
                    try {
                        s.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        System.exit(exitStatus);
    }
}
Run Code Online (Sandbox Code Playgroud)