Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure internet bandwidth

I have a problem and can't find answers. I would like to measure internet bandwidth with java, but I don´t know how.

It would be great to get some hints; I know that I have to open a socket and send it to a defined server, get it back and then use the time.

But how would I code this?

like image 850
J2A Avatar asked Dec 09 '25 20:12

J2A


2 Answers

Well I'd implement this simply by downloading a fixed size file. Not tested, but something along these lines should work just fine

byte[] buffer = new byte[BUFFERSIZE];
Socket s = new Socket(urlOfKnownFile);
InputStream is = s.getInputStream();
long start = System.nanoTime();
while (is.read(buffer) != -1) continue;
long end = System.nanoTime();
long time = end-start;
// Now we know that it took about time ns to download <filesize>. 
// If you don't know the correct filesize you can obviously use the total of all is.read() calls.
like image 168
Voo Avatar answered Dec 12 '25 09:12

Voo


How about fixing an arbitrary amount of time and send the data respecting it?

For example, let's say i want my server to limit it's bandwidth usage to 100Bytes/s. So i fix 1 second and send the data as long as it does not goes beyond 1 second and 100 Bytes.

Here's some pseudocode to show what I'm talking about:

timer_get (a);
sent_data = 0;

while (not_finished_sending_data)
{
    timer_get (b);
    if ((b - a) < 1 ) // 1 second
    {
        if (sent_data < 100) // 100 bytes
        {
            // We actually send here
            sent_data += send();
        }
    }
    else
    {
        timer_get (a);
        sent_data = 0;
    }
}
like image 38
alexdantas Avatar answered Dec 12 '25 11:12

alexdantas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!