我正在开发两个移动应用程序(Android 和 iOS),我必须发现网络中的所有主机。
我实现了ping某个范围内的所有IP地址的功能,例如,如果我的IP地址是192.168.1.3,我扫描这个范围192.168.1.1/192.168.1.255。
该功能发现了一些主机但不是全部,我不明白原因,我使用“Fing”应用程序来比较我的结果,在这种情况下我的功能发现了 18/20 台主机但发现了 43 台主机(全部)。
另一个问题是计算时间,我使用线程但 ping 解决方案浪费了更多时间来“ping”所有地址。
如何发现网络中的所有主机?
有人可以向我解释一下原因吗,因为我无法找到像 fing 这样的所有主机?
我使用的源代码:
private static final int NB_THREADS = 10;
public void doScan() {
Log.i(LOG_TAG, "Start scanning");
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for(int dest=0; dest<255; dest++) {
String host = "192.168.1." + dest;
executor.execute(pingRunnable(host));
}
Log.i(LOG_TAG, "Waiting for executor to terminate...");
executor.shutdown();
try { executor.awaitTermination(60*1000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { }
Log.i(LOG_TAG, "Scan finished");
}
private Runnable pingRunnable(final String host) {
return new Runnable() {
public void run() {
Log.d(LOG_TAG, "Pinging " + host + "...");
try {
InetAddress inet = InetAddress.getByName(host);
boolean reachable = inet.isReachable(1000);
Log.d(LOG_TAG, "=> Result: " + (reachable ? "reachable" : "not reachable"));
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Not found", e);
} catch (IOException e) {
Log.e(LOG_TAG, "IO Error", e);
}
}
};
}
最佳答案
当 fing 扫描我的家庭网络时,我运行了一个数据包捕获(如下所示),它似乎不使用 ping,而是使用 arp 请求。它按顺序扫描所有 IP,因此您可能只需要调整代码以使用 arp 请求。
(192.168.1.167是我手机的IP)
sudo tcpdump -ni eth0 host 192.168.1.167
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
...
01:18:32.695316 ARP, Request who-has 192.168.1.2 tell 192.168.1.167, length 46 01:18:32.715596 ARP, Request who-has 192.168.1.4 tell 192.168.1.167, length 46 01:18:32.725965 ARP, Request who-has 192.168.1.5 tell 192.168.1.167, length 46 01:18:32.736293 ARP, Request who-has 192.168.1.6 tell 192.168.1.167, length 46 01:18:32.746567 ARP, Request who-has 192.168.1.7 tell 192.168.1.167, length 46 01:18:32.761394 ARP, Request who-has 192.168.1.8 tell 192.168.1.167, length 46 01:18:32.769972 ARP, Request who-has 192.168.1.9 tell 192.168.1.167, length 46 01:18:32.777456 ARP, Request who-has 192.168.1.10 tell 192.168.1.167, length 46
...
更新:我忘了提到 fing 还运行 mac 查找,您可以获取 fing 列出的任何 Mac 并在以下站点上确认它:https://www.wireshark.org/tools/oui-lookup.html。该应用程序似乎执行其他请求和查找,但我相信这里解释了基本内容。
关于android - 如何扫描并发现网络中的所有主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37676895/