gpt4 book ai didi

java - 通过 android java 检测连接在网络上的计算机

转载 作者:行者123 更新时间:2023-12-02 06:10:02 25 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序来通过套接字连接与 Windows 服务进行通信。该代码正在运行,但我想添加检测本地网络上连接的设备的功能,以便应用程序可以确定哪台计算机正在运行我想要的 Windows 服务,我也使用从该网站获得的以下代码。我的问题是下面的代码仅检测 Android 设备,而不检测我的笔记本电脑。我可以从我的笔记本电脑 ping 我的设备,也可以从我的设备 ping 我的笔记本电脑,那么从这里该怎么做呢?

public void checkHosts(String subnet) {
int timeout = 1000;
for (int i = 1; i < 254; i++) {
String host = subnet + "." + i;
try {
if (InetAddress.getByName(host).isReachable(timeout)) {

System.out.println(host + " is reachable");
System.out.println("Host Name: "
+ InetAddress.getByName(host).getHostName());
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

最佳答案

InetAddress.isReachable() 不太可靠。如果 ICMP 消息被阻止,您将无法得到答复。

您可以做的是发送广播消息。您的服务器应用程序必须监听此消息并回答它。这样你就可以获得服务器的IP地址并可以连接到它。您只需发送一条消息即可到达子网中的所有主机。

Example code for sending and receiving broadcast messages

关于java - 通过 android java 检测连接在网络上的计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com