2

我想检查端口是否打开,或者服务器是否正在其上运行。
我已经尝试过多种方式,比如“/system/bin/ping”和“InetAdress”,但如果我是对的,我无法用这些 ping 指定端口:/

这次我用 DatagramSockets 这样的想法做到了:

try { String messageStr="Hello!";
   int server_port = 25565;
   DatagramSocket s = new DatagramSocket();
   InetAddress local = InetAddress.getByName("11.11.11.11");
   int msg_length=messageStr.length();
   byte[] message = messageStr.getBytes();
   DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port); 
   textView1.setText("Inet");
   s.send(p); 
   textView1.setText("Send");
} catch (Exception e) {}

我收到“Inet”,但没有“发送”消息,所以我在发送时卡住了。我试图获取异常消息,它是 NetworkOnMainThreadException..

4

4 回答 4

2

您无法 ping 特定端口。“ping”是一个 ICMP 回显请求。ICMP 是一种互联网层协议,因此没有“端口”的概念。

您可以使用 aSocket尝试建立与端口的 TCP 连接。如果它连接了,那么某些东西正在监听 TCP 连接。如果它没有连接,那么它在某种程度上是无法访问的。

您可以使用 aDatagramSocket尝试将数据包发送到端口。如果它成功了,那么某些东西可能正在接收数据。如果它失败了,那么肯定出了问题(顺便说一句,如果接收到的 UDP 数据包被发送到一个未为 UDP 开放的端口,或者如果有东西在途中主动拒绝了数据包,则会发回 ICMP 错误消息)。

您必须使用上述两种方法来检查 TCP 和 UDP。

请注意,InetAddress默认情况下使用 ICMP 请求作为 ping,但如果它没有这样做的权限,它将回退到尝试建立 TCP 连接。但是,如果它确实有权生成 ICMP 数据包,则无法强制它尝试 TCP 连接。因此,如果您想使用该方法,只需使用Socket.

于 2013-08-17T01:56:34.807 回答
0

您可以尝试解析netstat命令的输出以检查是否在所需端口上侦听了某些内容。

所以使用ProcessBuilder, netstatcommand 和一些parsing逻辑。

于 2013-08-17T01:56:42.620 回答
0
public ServerSocket create_server_socket( InetAddress[] ips, int[] ports) throws IOException {

    for( InetAddress ip: ips ) {
        for (int port : ports) {
            try {
                return new ServerSocket(port,0,ip);
            } catch (IOException ex) {
                continue; // try next port
            }
        }
        //try next ip
     }

    // if the program gets here, no ip:port in the range was found
    throw new IOException("no free ip:port found");
}
于 2013-08-17T02:03:35.513 回答
0

不要试图找到打开的端口或服务器正在运行,只需让服务器广播服务并监听来自客户端的回复,请查看此链接:http ://home.heeere.com/tech-androidjmdns.html 希望这会有所帮助。

于 2013-08-17T02:05:58.300 回答