javaintellij-ideanetwork-programmingsigaroshi

How to get internet speed and CPU temperatures in java


I need to get the internet speed (upload and download per second) in java. I'm currently using the Sigar and Oshi libraries but none of them shows me the speed as I would like.

On the network I found this class using Sigar to see the connection speed but I find the values completely wrong.

With Oshi I can not find the speed per second.

Some help?

In intellij console the values are wrong compared with speedtest: In intellij console the values are wrong compared with speedtest


Solution

  • You need to update the network stats

    You need to divide the amount of bytes received on the time that has passed

    You'll get better results from sleeping/waiting for a bit longer. There's a few interesting facts of Java, one of them being that asking for a sleep time of Nms won't necessarily have the thread sleep for that amount of time (it's more along the line of asking the thread to "sleep as close to Nms as you are able").

    The code should look more like:

    long download1 = net.getBytesRecv();
    long timestamp1 = net.getTimeStamp();
    Thread.sleep(2000); //Sleep for a bit longer, 2s should cover almost every possible problem
    net.updateNetworkStats(); //Updating network stats
    long download2 = net.getBytesRecv();
    long timestamp2 = net.getTimeStamp();
    System.out.println("prova " + (download2 - download1)/(timestamp2 - timestamp1));
    //Do the correct calculations
    

    This solution is here with oshi library. Thanks to YoshiEnVerde