I'm trying to detect devices connected to the network I'm currently on by pinging every one of them, and checking the "reachable" value. Here's the piece of code responsible for that, cycling through the IPs, pinging them and checking response:
for (int i = 1; i <= 254; i++) {
String addr = IPAddress;
addr = addr.substring(0, addr.lastIndexOf('.') + 1) + i;
InetAddress pingAddr = InetAddress.getByName(addr);
//skips the IP of 'this' device
if (pingAddr.getHostAddress().equals(IPAddress)) { continue; }
try {
//ping command
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 -w 1 " + addr);
boolean reachable = (p1.waitFor() == 0);
if (reachable) {
//add to list, if reachable
addrs.add(pingAddr);
}
} catch (IOException ex) {
} catch (InterruptedException ex) {
}
}
For some reason, this piece of code detects only some devices. I have 3 laptops, 2 android devices and 1 PC to test on. Out of these, it successfuly detects 2 of the 3 laptops, both android devices and it fails to detect the PC. You can notice the "-w 1" in the command, I tried setting that to 100, only change was it was taking ages to finish, and still found the same devices.
I also already tried this method:
INetAddress.isReachable(int timeout);
But it turned even worse, since - at least what i found - it uses TCP echo, which not all the devices respond to (only my android devices did).
Also, the pinging is really slow. I already divided it into 4 threads, but still it could use a speed boost.
So, my final question would be: Why is the ping command not able to detect every device & is there any other method you could think of to achieve my goal?