How to calculate network usage for transmission and reception

How can I calculate the network usage for transmitting and receiving either with C or from a shell script?

My system is embedded Linux. My current method is to write the bytes received (b1), wait 1 second, then write again (b2). Then, knowing the link speed, I calculate the percentage of the used bandwidth.

get usage = (((b2 - b1) * 8) / link_speed) * 100

Is there a better way?

+2


source to share


2 answers


thanks to "csl" for pointing me in the direction of vnstat. using the vnstat example, this is how I calculate the network usage.



#define FP32 4294967295ULL
#define FP64 18446744073709551615ULL
#define COUNTERCALC(a,b) ( b>a ? b-a : ( a > FP32 ? FP64-a-b : FP32-a-b))
int sample_time = 2; /* seconds */
int link_speed = 100; /* Mbits/s */
uint64_t rx, rx1, rx2;
float rate;

/* 
 * Either read:
 * '/proc/net/dev' 
 * or 
 * '/sys/class/net/%s/statistics/rx_bytes'
 * for bytes received counter
 */

rx1 = read_bytes_received("eth0"); 
sleep(sample_time); /* wait */
rx2 = read_bytes_received("eth0");

/* calculate MB/s first the convert to Mbits/s*/
rx = rintf(COUNTERCALC(rx1, rx2)/(float)1048576);
rate = (rx*8)/(float)sample_time;

percent = (rate/(float)link_speed)*100;

      

0


source


Check out open source programs that do something like this.

A little tool called vnstat came up in my search .

It tries to query for the / proc filesystem if available, and uses getifaddrs for systems that don't have one. It then fetches the correct AF_LINK interface, retrieves the appropriate if_data structure, and then reads the transmitted and received bytes, for example:



ifinfo.rx = ifd->ifi_ibytes;
ifinfo.tx = ifd->ifi_obytes;

      

Also remember that sleep () can sleep longer than exactly 1 second, so you should probably use a high resolution timer (wall clock) in your equation - or you can delve into if-functions and structures to see, find something suitable for your task.

+3


source







All Articles