代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何计算发送和接收的网络利用率

  •  2
  • Andrew  · 技术社区  · 16 年前

    如何使用C或shell脚本计算传输和接收的网络利用率?

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

    接收利用率=((b2-b1)*8)/链路速度)*100

    有更好的方法吗?

    2 回复  |  直到 16 年前
        1
  •  3
  •   csl    16 年前

    查看执行类似操作的开源程序。

    我的搜索找到了一个叫做 vnstat .

    它尝试查询/proc文件系统(如果可用),并使用 getifaddrs 对于没有它的系统。然后它获取正确的af_链接接口,获取相应的if_数据结构,然后读取发送和接收的字节,如下所示:

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

    还请记住,sleep()的睡眠时间可能会超过1秒钟,因此您应该在公式中使用高分辨率(挂钟)计时器,或者深入研究if函数和结构,以查看是否找到适合您任务的内容。

        2
  •  0
  •   Andrew    16 年前

    感谢“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;
    
    推荐文章