C语言 - 网卡流量统计信息获取

背景:我们需要测量brpc框架的通信性能,包括latency, MBps, qps

其中,latency, qps是可以查的,但是MBps需要自己算。

于是考虑读取/proc/net/dev的相关数据进行计算。

代码如下:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

// 更改为你要监测的网卡名称,可以通过ifconfig获得
#define INTERFACE_NAME "enth0" 

unsigned long long tic_bytes;
unsigned long long toc_bytes;

// 读取指定网卡的统计信息
int read_interface_stats(const char *interface_name, bool is_tic) {
    FILE *file = fopen("/proc/net/dev", "r");
    if (file == NULL) {
        perror("Failed to open /proc/net/dev");
        return -1;
    }

    char line[256];
    while (fgets(line, sizeof(line), file)) {
        if (strstr(line, interface_name) != NULL) {
            if (is_tic) {
            	// 读取bytes的相关信息,用%*s跳过无用字符串
                sscanf(line, "%*s %llu", &tic_bytes);
            }
            else {
                sscanf(line, "%*s %llu", &toc_bytes);
            }
        
            fclose(file);
            return 0;
        }
    }

    fclose(file);
    return -1;
}

int main() {
    double interval = 2.0; // 采样间隔,单位为秒

    while (1) {
        if (read_interface_stats(INTERFACE_NAME, true) == -1) {
            printf("Failed to read interface stats\n");
            return 1;
        }

        sleep((unsigned int)interval);

        if (read_interface_stats(INTERFACE_NAME, false) == -1) {
            fprintf(stderr, "Failed to read interface stats\n");
            return 1;
        }

        double bps = (toc_bytes - tic_bytes) / interval;
        printf("bytes/s: %.2f\n", bps);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PenguinLeee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值