unix socket实现网卡接口多线程监控 rx_packets, tx_packets, rx_errs, tx_errs等数据

废话不多说,直接上代码:

客户端:

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/un.h>
#include <string.h>
#include <stdio.h>
#include <ifaddrs.h>
#include <sys/ioctl.h>
#include <iostream>
#include <net/if.h>
#include <net/if_arp.h> 


using namespace std;

#define PORT  8890
#define BUFFER_SIZE 1024
#define MAXINTERFACES 64 
const char *filename="/tmp/sss";

 
struct net{
    char name[128];
    char mac[30];
    char ip[30];
    char state[30];
    unsigned long long rx_bytes;
    unsigned long long rx_packets;
    unsigned long long rx_errs;
    unsigned long long rx_drop;
    
    unsigned long long tx_bytes;
    unsigned long long tx_packets;
    unsigned long long tx_errs;
    unsigned long long tx_drop;
};
 
enum if_item
{
    RX_BYTES = 0,
    RX_PACKETS,
    RX_ERRS,
    RX_DROP,
    RX_FIFO,
    RX_FRAME,
    RX_COMPRESSED,
    RX_MULTICAST,
    TX_BYTES,
    TX_PACKETS,
    TX_ERRS,
    TX_DROP,
    TX_FIFO,
    TX_COLLS,
    TX_CARRIER,
    TX_COMPRESSED,
    IF_ITEM_MAX
};

int AdapterCount(struct net* Adapter)
{
    int nCount=0;
    FILE* fp = fopen("/proc/net/dev", "r");
    if(!fp)
    {
        perror("fopen /proc/net/dev");
        exit(0);
    }
    char szline[1024] = {0};
    fgets(szline, sizeof(szline), fp);
    fgets(szline, sizeof(szline), fp);
 
    int i=0;
    struct ifreq ifr_mac_ip;
    int s = socket(AF_UNIX, SOCK_STREAM, 0);
    memset(szline, 0, sizeof(szline));
    //
    while(fgets(szline, sizeof(szline), fp) != NULL)
    {
        //
        string name = szline;
        int p1 = name.find_first_of(':', 0);
        name = name.substr(0, p1);
        int p2 = name.rfind(' ', -1);
        if(p2 != -1)
        {
            name = name.substr(p2+1, -1);
        }
        memcpy(Adapter[i].name, name.c_str(), strlen(name.c_str()));
 
        
        unsigned long long data[32] = {0};
        sscanf(szline+p1+1, "%llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu", 
            data + RX_BYTES,
            data + RX_PACKETS,
            dat

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值