Search code examples
javanetwork-programmingicmp

Alternative to isReachable in InetAddress class


I want to check whether an active internet connection exists or not. For that I found out I can do that with the isReachable() method from the InetAddress class. Unfortunately (as the JavaDoc suggests and this post verifies), this only works with root privilegies, what is no solution to my problem.

When I run the following code, isReachable is always false:

InetAddress address = InetAddress.getByName("173.194.35.3"); //e.g. google
boolean isReachable = address.isReachable(2000); //ms

Therefore, I am searching for a good alternative to check for an active internet connection without the necessity of root privilegies.

Thank you!


Solution

  • It can be old, but I had the same problem and after read those answers I found this amazing library icmp 4j and solved all my problems. You can download the source code here and use in your project something like this

    // request
    final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest ();
    request.setHost ("192.168.0.101");
    
    // repeat a few times
    for (int count = 1; count <= 4; count ++) {
    
    // delegate
    final IcmpPingResponse response = IcmpPingUtil.executePingRequest (request);
    
    // log
    final String formattedResponse = IcmpPingUtil.formatResponse (response);
    System.out.println (formattedResponse);
    
    // rest
    Thread.sleep (1000);
    }