NullPointerException
NullPointerException

Reputation: 37701

How to get internet connection latency/ping?

I need to get the current internet connection latency in ms. After doing a research in Stack Overflow, I found this code to get the latency:

            String host = "www.google.com";
            int timeout = 10000;
            long beforeTime = System.currentTimeMillis();
            boolean reachable =  InetAddress.getByName(host).isReachable(timeout);
            long afterTime = System.currentTimeMillis();
            long latency = afterTime - beforeTime;

I also tried with 8.8.8.8 which is google DNS IP, and the result is the same.

The problem is that latency variable is very big in some devices, abnormal value, for example, sometimes 60, sometimes 400 ms in a Pixel XL, and always around 3000 ms in a slow device from 2014 with android 5.0. also in the simulator is always around 6000 ms, but I think that simulator doesn't give correct values.

In that device with Android 5.0 with around 3000 ms of latency returned by that code, when I open www.google.com it's super fast, and if I try various online internet connection tests in the navigator of the device, the latency is 30 ms, so those 3000 ms of latency are false. It's the same with the other devices.

How can latency be measured correctly in Android?

Upvotes: 0

Views: 1282

Answers (0)

Related Questions