如何在 linux/Mac OSX 中获取网络适配器统计信息? [英] How to get network adapter stats in linux/Mac OSX?

查看:32
本文介绍了如何在 linux/Mac OSX 中获取网络适配器统计信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Linux 和 MacOSX 上使用 C 语言获取网络统计信息的方法.具体来说,我需要监控从系统上每个网络适配器上传和下载的字节数 - 我不需要进行数据包检查或区分协议,只需一个总字节数"计数器,我可以每隔一段时间轮询一次没事的.在 Windows 中,我可以通过 GetIfTable(列出网络适配器)和 GetIfEntry(读取统计信息)使用 iphlpapi.dll 库来执行此操作,但是我找不到 Linux/OSX 等效项.我对 C 的了解是相当基础的,所以我希望有一个不太复杂的解决方案.任何帮助将不胜感激!

I'm looking for a way to get hold of network stats in C on Linux and MacOSX. Specifically, I need to monitor the number of bytes uploaded and downloaded from each network adapter on the system - I don't need to do packet inspection, or differentiate between protocols, just a 'total bytes' counter which I can poll at intervals would be fine. In Windows I can do this using the iphlpapi.dll library via GetIfTable (to list the network adapters) and GetIfEntry (to read the stats), but I can't find the Linux/OSX equivalents. My knowledge of C is fairly basic so I would appreciate a solution that isn't too involved. Any help would be much appreciated!

推荐答案

Darwin netstat 源代码使用 sysctl.下面是一些在 OSX 上打印进出字节数的代码:

The Darwin netstat source code uses sysctl. Here's some code that prints the number of bytes in and out on OSX:

#import <Foundation/Foundation.h>
#include <sys/sysctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/route.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int mib[] = {
        CTL_NET,
        PF_ROUTE,
        0,
        0,
        NET_RT_IFLIST2,
        0
    };
    size_t len;
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        fprintf(stderr, "sysctl: %s\n", strerror(errno));
        exit(1);
    }
    char *buf = (char *)malloc(len);
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        fprintf(stderr, "sysctl: %s\n", strerror(errno));
        exit(1);
    }
    char *lim = buf + len;
    char *next = NULL;
    u_int64_t totalibytes = 0;
    u_int64_t totalobytes = 0;
    for (next = buf; next < lim; ) {
        struct if_msghdr *ifm = (struct if_msghdr *)next;
        next += ifm->ifm_msglen;
        if (ifm->ifm_type == RTM_IFINFO2) {
            struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
            totalibytes += if2m->ifm_data.ifi_ibytes;
            totalobytes += if2m->ifm_data.ifi_obytes;
        }
    }
    printf("total ibytes %qu\tobytes %qu\n", totalibytes, totalobytes);
    [pool drain];
    return 0;
}

这篇关于如何在 linux/Mac OSX 中获取网络适配器统计信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆