检查端口是在Android / Java的开放 [英] Check if Port is open on Android/Java

查看:448
本文介绍了检查端口是在Android / Java的开放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查如果一个端口是开放的,或服务器上运行。结果
我已经尝试了多种方式,像/系统/斌/平和InetAdress,但如果IM权我不能ping一个指定的端口与这些:/

I would like to check if a port is open, or a server is running on it.
I already tried it in multiple ways, like with "/system/bin/ping" and "InetAdress", but if im right I cant ping a specified port with these :/

这一次,我的想法DatagramSockets像这样使得它:

This time i made it with the idea DatagramSockets like so:

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 ..

I get the "Inet", but no "Send" message, so i get stuck at sending. I tried to get the exception message, and it is NetworkOnMainThreadException..

推荐答案

您不能ping一个特定端口。 A平是ICMP回应请求。 ICMP是一个互联网层协议,因此没有一个端口的概念。

You cannot ping a specific port. A "ping" is an ICMP echo request. ICMP is an internet layer protocol and as such has no concept of a "port".

您可以使用插座来试图建立TCP连接的端口。如果它连接,那么什么是监听TCP连接。如果它不连接,那么它在某些方面不可达。

You could use a Socket to attempt to establish a TCP connection to the port. If it connects, then something was listening for TCP connections. If it doesn't connect, then it was unreachable in some way.

您可以使用的DatagramSocket 试图发送一个数据包的端口。如果成功,那么就有可能是接收数据。如果失败,那么就有肯定出了问题(顺便说一句,如果接收到UDP数据包被发送到未打开UDP的端口,或者如果事情主动拒绝的方式将数据包发送一个ICMP错误消息回)。

You could use a DatagramSocket to attempt to send a packet to the port. If it succeeds, then something is probably receiving data. If it fails, then something definitely went wrong (incidentally, an ICMP error message is sent back if a UDP packet is received that is addressed to a port that is not open for UDP, or if something actively refuses the packet on the way).

您不得不使用上述两种检查TCP和UDP。

You'd have to use both of the above to check both TCP and UDP.

注意的InetAddress 使用了ICMP请求的默认平,但如果没有权限做到这一点,它会依傍试图建立一个TCP连接代替。然而,在的情况下,它的确实的权限产生ICMP包,有没有办法迫使它在尝试建立TCP连接,而不是。所以,如果你想用这种方法,只需要使用插座

Note that InetAddress uses an ICMP request as ping by default, but if it does not have permission to do that, it will fall back on attempting to establish a TCP connection instead. However, in the case that it does have permission to generate ICMP packets, there is no way to force it to attempt a TCP connection instead. So if you want to use that method, just use a Socket.

这篇关于检查端口是在Android / Java的开放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆