Reputation: 1315
I tried to Parse txBytes,rxBytes,rxPackets,txPackets from /proc/net/dev using c. Output is not as i expected. Here is the core of my code
while (fgets(buf, sizeof(buf), file) != NULL) {
conv = sscanf( buf, "%[^:]: %Lu %*u %*u %*u %*u %*u %*u %*u %Lu %*u %*u %*u %*u %*u %*u %*u", ifname, &rxBytes, &txBytes );
printf("%s %Lu %Lu\n",ifname,rxBytes,txBytes);
conv = 0;
ifacesCount++;
}
Here the file is /proc/net/dev and buf size is 500. I want to extract the interface name,txBytes,rxBytes,rxPackets,txPackets
Upvotes: 1
Views: 2660
Reputation: 740
From your code sample, I wrote the following:
#include <stdio.h>
int main() {
FILE *fp = fopen("/proc/net/dev", "r");
char buf[200], ifname[20];
unsigned long int r_bytes, t_bytes, r_packets, t_packets;
// skip first two lines
for (int i = 0; i < 2; i++) {
fgets(buf, 200, fp);
}
while (fgets(buf, 200, fp)) {
sscanf(buf, "%[^:]: %lu %lu %*lu %*lu %*lu %*lu %*lu %*lu %lu %lu",
ifname, &r_bytes, &r_packets, &t_bytes, &t_packets);
printf("%s: rbytes: %lu rpackets: %lu tbytes: %lu tpackets: %lu\n",
ifname, r_bytes, r_packets, t_bytes, t_packets);
}
fclose(fp);
return 0;
}
This outputs:
lo: rbytes: 22975300 rpackets: 459506 tbytes: 22975300 tpackets: 459506
wlp2s0: rbytes: 2419131107 rpackets: 1820658 tbytes: 109438292 tpackets: 877583
eno1: rbytes: 15984078 rpackets: 55391 tbytes: 3078636 tpackets: 13019
Hope that helps you :)
Upvotes: 2