2009-10-06 43 views
2

如何计算网络利用率为发送和接收或者使用C或shell脚本?如何计算网络利用率为发送和接收

我的系统是一个嵌入式Linux。我目前的方法是记录收到的字节(b1),等待1秒,然后再次记录(b2)。然后知道链路速度,我计算使用的接收带宽的百分比。

接收利用率=(((B2 - B1)* 8)/ LINK_SPEED)* 100

是否有更好的方法?

+0

为什么你乘以(b2-b1)八? – csl 2009-10-06 13:16:56

+0

@csl:链接速度将在bitspersecond我想,这就是为什么改变字节位 – vpram86 2009-10-06 13:18:21

+0

@Aviator也许吧,但后来应该已经嵌入在不断_link_speed_ – csl 2009-10-06 13:19:01

回答

0

感谢'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; 
3

退房的开源程序,做类似的事情。

我的搜索出现了一个叫vnstat的小工具。

它试图查询/ proc文件系统(如果可用),并且对于没有它的系统使用getifaddrs。然后它获取正确的AF_LINK接口,获取相应的if_data结构,然后读出发送和接收的字节,这样的:

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

还记得睡眠()可能会睡超过正好1秒,那么你或许应该在你的公式中使用高分辨率(挂钟)定时器 - 或者你可以深入研究if函数和结构,看看你是否找到适合你的任务的东西。

+0

太棒了! :)只是寻找到它:) – vpram86 2009-10-06 13:25:20

+0

vnstat - 看起来很有希望,我要看看它。 – Andrew 2009-10-06 15:12:23