bash 如何计算传输和接收的网络利用率
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1525507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I calculate network utilization for both transmit and receive
提问by Andrew
How do I calculate network utilization for both transmit and receive either using C or a shell script?
如何使用 C 或 shell 脚本计算传输和接收的网络利用率?
My system is an embedded linux. My current method is to recorded bytes received (b1), wait 1 second, then recorded again (b2). Then knowing the link speed, I calculate the percentage of the receive bandwidth used.
我的系统是嵌入式linux。我目前的方法是记录接收到的字节(b1),等待 1 秒,然后再次记录(b2)。然后知道链接速度,我计算使用的接收带宽的百分比。
receive utilization = (((b2 - b1)*8)/link_speed)*100
接收利用率 = (((b2 - b1)*8)/link_speed)*100
is there a better method?
有没有更好的方法?
采纳答案by Andrew
thanks to 'csl' for pointing me in the direction of vnstat. using vnstat example here is how I calculate network utilization.
感谢“csl”为我指明了 vnstat 的方向。这里使用 vnstat 示例是我计算网络利用率的方法。
#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;
回答by csl
Check out open source programs that does something similar.
查看执行类似操作的开源程序。
My search turned up a little tool called vnstat.
我的搜索出现了一个名为vnstat的小工具。
It tries to query the /proc file system, if available, and uses getifaddrsfor systems that do not have it. It then fetches the correct AF_LINK interface, fetches the corresponding if_data struct and then reads out transmitted and received bytes, like this:
它尝试查询 /proc 文件系统(如果可用),并为没有它的系统使用getifaddrs。然后它获取正确的 AF_LINK 接口,获取相应的 if_data 结构,然后读出发送和接收的字节,如下所示:
ifinfo.rx = ifd->ifi_ibytes;
ifinfo.tx = ifd->ifi_obytes;
Also remember that sleep() might sleep longer than exactly 1 second, so you should probably use a high resolution (wall clock) timer in your equation -- or you could delve into the if-functions and structures to see if you find anything appropriate for your task.
还要记住 sleep() 的睡眠时间可能超过 1 秒,因此您可能应该在等式中使用高分辨率(挂钟)计时器——或者您可以深入研究 if 函数和结构,看看是否有任何合适的为您的任务。

