网络接口流量信息获取
2021-03-16, updated 2021-09-12
linux 记录网络接口流量信息的文件在/proc/net/dev
以下为c获相关信息示例
/*
* Inter-| Receive | Transmit
* face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
* ens33: 1378627 6509 0 0 0 0 0 0 1046428 4792 0 0 0 0 0 0
* lo: 10212375 78449 0 0 0 0 0 0 10212375 78449 0 0 0 0 0 0
* ens39: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
* ens38: 16144882 77529 0 0 0 0 0 0 368175 3317 0 0 0 0 0 0
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#undef long_t
#define long_t long long unsigned
typedef struct
{
char iface[32];
long_t rcv_bytes;
long_t rcv_packets;
long_t rcv_errs;
long_t rcv_drop;
long_t rcv_fifo;
long_t rcv_frame;
long_t rcv_compressed;
long_t rcv_multicast;
long_t snd_bytes;
long_t snd_packets;
long_t snd_errs;
long_t snd_drop;
long_t snd_fifo;
long_t snd_colls;
long_t snd_carrier;
long_t snd_compressed;
}dev_st;
int main()
{
FILE *fp = NULL;
char buf[128] = {0};
dev_st st[10];
fp = fopen("/proc/net/dev", "r");
if(fp == NULL) {
perror("fopen");
return -1;
}
int i = 0;
fgets(buf, sizeof(buf), fp);
fgets(buf, sizeof(buf), fp);
memset(st, 0, sizeof(dev_st));
while(fgets(buf, sizeof(buf), fp)) {
{
// sscanf(buf, "%s %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu",
sscanf(buf, "%6s: %7llu %7llu %4llu %4llu %4llu %5llu %10llu %9llu %8llu %7llu %4llu %4llu %4llu %5llu %7llu %10llu",
st[i].iface,
&st[i].rcv_bytes,
&st[i].rcv_packets,
&st[i].rcv_errs,
&st[i].rcv_drop,
&st[i].rcv_fifo,
&st[i].rcv_frame,
&st[i].rcv_compressed,
&st[i].rcv_multicast,
&st[i].snd_bytes,
&st[i].snd_packets,
&st[i].snd_errs,
&st[i].snd_drop,
&st[i].snd_fifo,
&st[i].snd_colls,
&st[i].snd_carrier,
&st[i].snd_compressed);
st[i].iface[strlen(st[i].iface)-1] = '\0';
}
i++;
}
for(i=0;i < 2;i ++)
{
printf("st[%d].iface:%s\n", i, st[i].iface);
printf("st[%d].rcv_bytes:%llu\n", i, st[i].rcv_bytes);
printf("st[%d].rcv_packets:%llu\n", i, st[i].rcv_packets);
printf("st[%d].rcv_errs:%llu\n", i, st[i].rcv_errs);
printf("st[%d].rcv_drop:%llu\n", i, st[i].rcv_drop);
printf("st[%d].rcv_fifo:%llu\n", i, st[i].rcv_fifo);
printf("st[%d].rcv_frame:%llu\n", i, st[i].rcv_frame);
printf("st[%d].rcv_compressed:%llu\n", i, st[i].rcv_compressed);
printf("st[%d].rcv_multicast:%llu\n", i, st[i].rcv_multicast);
printf("st[%d].snd_bytes:%llu\n", i, st[i].snd_bytes);
printf("st[%d].snd_packets:%llu\n", i, st[i].snd_packets);
printf("st[%d].snd_errs:%llu\n", i, st[i].snd_errs);
printf("st[%d].snd_drop:%llu\n", i, st[i].snd_drop);
printf("st[%d].snd_fifo:%llu\n", i, st[i].snd_fifo);
printf("st[%d].snd_colls:%llu\n", i, st[i].snd_colls);
printf("st[%d].snd_carrier:%llu\n", i, st[i].snd_carrier);
printf("st[%d].snd_compressed:%llu\n", i, st[i].snd_compressed);
printf("----------------------------------------------------------\n");
}
return 0;
}