0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
NullPointerException
  • 36,107
  • 79
  • 222
  • 382
  • try multiple times and check the average – Alberto Sinigaglia Apr 26 '21 at 10:19
  • `isReachable` isn't really deterministic on what it actually does for specific devices.To get repeatable results, you should really do some specific network operation. You could utilize a socket for example: https://stackoverflow.com/a/45416203/2232127 . Regardless, you're usually constricted to use a server with some sort of controlled behaviour (e.g. easiest to use your own) otherwise you introduce all kinds of overhead which is unknown to you. – JensV Apr 26 '21 at 10:54
  • @JensV do you have a working piece of code of that? that non accepted solution is some kind of pseudocode sample without real class names or real use for example for that socket variable, etc.. – NullPointerException Apr 26 '21 at 10:59

0 Answers0