尝试增加超时.我用了大约5000毫秒,这对我很有帮助.
如果您不想等待5000ms * 254 = 21分钟,请尝试使用此代码并行ping到地址:
public static void getNetworkIPs() {
final byte[] ip;
try {
ip = InetAddress.getLocalHost().getAddress();
} catch (Exception e) {
return; // exit method,otherwise "ip might not have been initialized"
}
for(int i=1;i<=254;i++) {
final int j = i; // i as non-final variable cannot be referenced from inner class
new Thread(new Runnable() { // new thread for parallel execution
public void run() {
try {
ip[3] = (byte)j;
InetAddress address = InetAddress.getByAddress(ip);
String output = address.toString().substring(1);
if (address.isReachable(5000)) {
System.out.println(output + " is on the network");
} else {
System.out.println("Not Reachable: "+output);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start(); // dont forget to start the thread
}
}
为我工作完美.