linux网络数据统计

来源:互联网 发布:mac桌面卸载图标 编辑:程序博客网 时间:2024/06/08 03:24
//file: read_flow.cpp// g++ -o read_flow read_flow.cpp -Wall//use: read_flow eth1 3   每3秒刷新一下eth1的流量#include <stdio.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h>int main(int argc, char *argv[]){    if (argc < 2) {printf("usage:read_flow dev [time]\n");return 1;    }    int nDevLen = strlen(argv[1]);    if (nDevLen < 1 || nDevLen > 100) {printf("dev length too long\n");return 1;    }    int nTimeSpan = 1;    if (argc >= 3) {nTimeSpan = atoi(argv[2]);if (nTimeSpan < 1) {    nTimeSpan = 1;}    }    FILE *fp;    //循环输出    unsigned long long last_rx_bytes = 0;    unsigned long long last_tx_bytes = 0;    unsigned long long nRxBytes = 0;    unsigned long long nTxBytes = 0;    do {if ((fp =     popen("cat /proc/net/dev | awk '/wlan0/{print $2\" \"$10}'",   "r")) == NULL) {    printf("/proc/net/dev not exists!\n");    return 1;} else {    fscanf(fp, "%llu %llu", &nRxBytes, &nTxBytes);    pclose(fp);    //printf("RX: %llu bytes   TX %llu bytes", nRxBytes, nTxBytes);}unsigned long long nTempRxBytes = nRxBytes - last_rx_bytes;unsigned long long nTempTxBytes = nTxBytes - last_tx_bytes;if(0 != last_rx_bytes && 0 != last_tx_bytes)printf("\tRX:\t%9.2fkbps\t\tTX:\t%9.2fkbps",       (double) nTempRxBytes / nTimeSpan / (1024/8), //covert byte to bit       (double) nTempTxBytes / nTimeSpan / (1024/8));last_rx_bytes = nRxBytes;last_tx_bytes = nTxBytes;printf("\n");sleep(nTimeSpan);    } while (1);    return 1;}


原创粉丝点击