[英]How to discover host in a WiFi network in Android (JAVA)
I'm developing an Android application, I have to discover each hosts in a WiFi network, I have implemented a function that "ping" all IP address between 1 and 255 of a certain network. 我正在开发一个Android应用程序,我必须发现WiFi网络中的每个主机,并且实现了一项功能,可以“ ping”某个网络的1到255之间的所有IP地址。
This solution it work perfectly, but there is a problem, the execution time.. Every time that i start my application I wait about 256 second, it too long, i can't wait this time. 此解决方案可以正常工作,但是有一个问题,执行时间。每次我启动应用程序时,我等待大约256秒,这太长了,我等不及了。
This is my source code (i found this code on Stack, i modified the code to work in my condition): 这是我的源代码(我在Stack上找到了此代码,我修改了代码以使其在我的情况下可以正常工作):
public class ScanNetwork {
ArrayList < String > hosts;
int i;
boolean finish = false;
public ArrayList < String > ScanNetwork(String ipAddress) {
hosts = new ArrayList < String > ();
final String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
for (i = 0; i < 256; i++) {
String currentHost = subnet + "." + i;
Process p1 = null;
int returnVal = 0;
try {
p1 = Runtime.getRuntime().exec("ping -w 50 -c 1 " + currentHost);
returnVal = p1.waitFor();
} catch (IOException e) {
System.out.println("Log: " + e.toString());
} catch (InterruptedException e) {
System.out.println("Log: " + e.toString());
}
boolean reachable = (returnVal == 0);
if (reachable) {
if (!hosts.contains(currentHost)) {
hosts.add(currentHost);
System.out.println(currentHost);
}
}
}
return hosts;
}
}
This source code is perfect but the execution time is excessive, there are other way to obtain all the host in the network ? 该源代码是完美的,但是执行时间过长,还有其他方法来获取网络中的所有主机吗?
How i can solve this problem ? 我该如何解决这个问题?
The problem I see is that you are doing all the pings sequentially - the loop is spending most of its time waiting for replies. 我看到的问题是,您正在按顺序执行所有ping操作-循环将大部分时间都花在等待答复上。 Try starting up a few AsyncTasks, each of which has an assigned range of addresses to search, and let them work in parallel. 尝试启动一些AsyncTask,每个AsyncTask都有分配的地址范围进行搜索,并使其并行工作。
Note that for a typical 192.168.1.x network, ".0" (all 0 bits) ".255" (all 1 bits) will not correspond to a host and doesn't need checking. 请注意,对于典型的192.168.1.x网络,“。0”(全0位)“。255”(全1位)将不对应于主机,也不需要检查。
Also don't forget that not everybody responds to a ping (this is more likely in a corporate network, less so at home) 另外请不要忘记,并非每个人都对ping做出响应(在公司网络中这种可能性更大,而在家中的可能性较小)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.