【发布时间】:2016-06-07 10:30:52
【问题描述】:
我正在开发两个移动应用程序(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);
}
}
};
}
【问题讨论】:
-
没有万无一失的方法。
-
如果你想实现这种功能,你应该看看nmap's port scanning techniques。
标签: android networking