Harshit
Harshit

Reputation: 5157

java inetaddress isreachable not working

I am trying to ping 200s of IPs in a loop in every 10 seconds. So, this loop gets executed in every 10 seconds. I was using this code to ping the IPs

for (i = 0; i <= 200; i++ )
{
   ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", *SOMEIP*);
   Process proc = processBuilder.start();

   int returnVal = proc.waitFor();
}

This is just the part of my code. I am creating separate thread for every ping because if 100 IPs are down, then it will take more than 300 seconds to ping each & every IP sequentially. So, created separate threads. But the problem was that whenever the loop gets executed, then the PCs CPU usage reaches to 90%, which is not good for a critical system. So I change the program to this one.

for (i = 0; i <= 200; i++ )
{
   InetAddress inet = InetAddress.getByName(*SOMEIP*);
   System.out.println(inet.isReachable(3000) ? "Host is reachable" : "Host is NOT reachable");

}

In the above code also, I am creating separate thread for each Ping because of the same problem. Now, here I am getting another problem. This code is giving unexpected result. The IPs which are pingable are also showing not reachable using above code. Why this is happening ?

Is the isReachable function buggy ?

I am using Windows OS.

Thanks

Upvotes: 0

Views: 2511

Answers (1)

user207421
user207421

Reputation: 311028

Because they test different things, or rather they operate in different ways.

ping uses ICMP.

In practice isReachable() uses TCP.

Upvotes: 2

Related Questions