代码之家  ›  专栏  ›  技术社区  ›  roh

如何在Linux/MacOSX中获取网络适配器统计信息?

  •  8
  • roh  · 技术社区  · 17 年前

    我正在寻找一种方法来获取Linux和MacOSX上C语言的网络统计信息。具体来说,我需要监视从系统上的每个网络适配器上载和下载的字节数-我不需要进行数据包检查,也不需要区分协议,只需要一个“总字节”计数器,我可以每隔一段时间轮询它就可以了。在windows中,我可以通过getiftable(列出网络适配器)和getifentry(读取统计数据)使用iphlpapi.dll库来完成这项工作,但找不到linux/osx的等效版本。我对C语言的了解是相当基础的,所以我希望有一个不太复杂的解决方案。任何帮助都将不胜感激!

    3 回复  |  直到 14 年前
        1
  •  21
  •   Stefan    17 年前

    达尔文netstat源代码使用sysctl。 下面是一些在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;
    }
    
        2
  •  2
  •   Duck    17 年前

    我不能和OSX说话,但在Linux上可以看看/proc/net/dev。

    如果执行“cat/proc/net/dev”,则应看到包括“bytes”在内的统计信息,即接口发送或接收的数据的总字节数。您可以在自己的程序中读取该文件。

    编辑:

    我没读你的全部问题。 This article 应该可以帮助您开始使用/proc,并在/proc/net/dev上有一节。

    另外,要列出可以调用的接口 ioctl 与 SIOCGIFCONF 选择权。您可以在google上搜索一个关于如何遍历返回数据的不错的代码示例。或者您可以简单地从上面提到的/proc.net/dev数据中提取它,这应该更容易。

        3
  •  2
  •   Javier    14 年前

    Linux上:

    • 低电平:检查 /sys/class/net/eth0/statistics/
    • 稍微高一点: ip -s link show eth0
    • 图解: iftop
    • 互动式: iptraf