linux网络数据统计

//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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值