我正在开发一个Android应用程序,我必须实现一个功能,发现我所连接的网络的所有主机(例如WiFi)。
我实现了一个有效的功能,这是我的代码:
public class ScanNetwork {
private static final int NB_THREADS = 10;
private ArrayList < String > hosts;
public ArrayList < String > ScanNetwork(String ipAddress) {
hosts = new ArrayList <> ();
String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for (int dest = 0; dest < 255; dest++) {
String host = subnet + "." + dest;
executor.execute(pingRunnable(host));
}
executor.shutdown();
try {
executor.awaitTermination(60 * 1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {}
return hosts;
}
private Runnable pingRunnable(final String host) {
return new Runnable() {
public void run() {
try {
InetAddress inet = InetAddress.getByName(host);
boolean reachable = inet.isReachable(1000);
if (reachable) {
hosts.add(host);
}
} catch (UnknownHostException e) {
System.out.println("Log: " + e);
} catch (IOException e) {
System.out.println("Log: " + e);
}
}
};
}
}
此代码适用于某类IP,例如192.168.1.10,但不适用于10.1.25.1。
问题很简单,如何在考虑各种IP的情况下实现发现某个网络中所有主机的功能?