您的位置:首页 > 运维架构 > Linux

linux 流量统计小程序

2015-07-02 16:59 603 查看
源码如下:

//2015/7/2 10:30:35
//gino
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define FLOW_RX_FILE    "/sys/class/net/eth0/statistics/rx_bytes"
#define FLOW_TX_FILE    "/sys/class/net/eth0/statistics/tx_bytes"
#define FLOW_STATISTICS     "/tmp/statistics"
#define DATA_BUF_SIZE       1024

int main(int argc, char **argv){

int flowRx_fd, flowTx_fd, flowSt_fd, data_size ;
char RX_buf[DATA_BUF_SIZE] , TX_buf[DATA_BUF_SIZE];
FILE *flowSt_pin = NULL;

if((flowRx_fd = open(FLOW_RX_FILE, O_RDONLY)) == -1){
fprintf(stderr, "RX_open: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}

if((flowTx_fd = open(FLOW_TX_FILE, O_RDONLY)) == -1){
fprintf(stderr, "TX_open: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}

if((flowSt_fd = open(FLOW_STATISTICS, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) == -1){
fprintf(stderr, "ST_open: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}

//将文件描述符转换成文件指针
flowSt_pin = fdopen(flowSt_fd, "w+");

while(1){

bzero(RX_buf,sizeof(RX_buf));
bzero(TX_buf,sizeof(TX_buf));

if((data_size = read(flowRx_fd,RX_buf,sizeof(RX_buf))) == -1){
fprintf(stderr, "read_rx: %s\n",strerror(errno));
}
RX_buf[data_size -1 ] = '\0';

if((data_size = read(flowTx_fd,TX_buf,sizeof(TX_buf))) == -1){
fprintf(stderr, "read_tx: %s\n",strerror(errno));
}
TX_buf[data_size -1 ] = '\0';

//JOSN格式  {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
fprintf(flowSt_pin,"{\"up_flow\":\"%s\",\"down_flow\":\"%s\"}\n",RX_buf, TX_buf);
fflush(flowSt_pin);

lseek(flowRx_fd, 0, SEEK_SET);
lseek(flowTx_fd, 0, SEEK_SET);

sleep(2);

//更改文件大小,保存向文件中写入的数据达到覆盖效果
ftruncate(flowSt_fd, 0);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: