如何在linux / Mac OSX中获取网络适配器统计信息?
发布时间:2020-12-14 02:54:53 所属栏目:Linux 来源:网络整理
导读:我正在寻找一种方法来获取 Linux和MacOSX上的C网络统计数据.具体来说,我需要监控从系统上的每个网络适配器上传和下载的字节数 – 我不需要进行数据包检查,也不需要区分协议,只需要一个’总字节’计数器,我可以间隔轮询没事的.在Windows中,我可以使用iphlpapi
我正在寻找一种方法来获取
Linux和MacOSX上的C网络统计数据.具体来说,我需要监控从系统上的每个网络适配器上传和下载的字节数 – 我不需要进行数据包检查,也不需要区分协议,只需要一个’总字节’计数器,我可以间隔轮询没事的.在Windows中,我可以使用iphlpapi.dll库通过GetIfTable(列出网络适配器)和GetIfEntry(读取统计信息),但我找不到Linux / OSX等价物.我对C的了解非常基础,所以我很欣赏一个不太复杂的解决方案.任何帮助将非常感激!
解决方法
Darwin 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,NET_RT_IFLIST2,0 }; size_t len; if (sysctl(mib,6,NULL,&len,0) < 0) { fprintf(stderr,"sysctl: %sn",strerror(errno)); exit(1); } char *buf = (char *)malloc(len); if (sysctl(mib,buf,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 %qutobytes %qun",totalibytes,totalobytes); [pool drain]; return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- linux – 用bash中的其他文件过滤文件
- linux中c“fopen”可以打开的最大文件数
- gitlab的安装配置与简单使用
- public-key – 是否可以使用gpg公钥来加密消息而无需导入密
- 任务1:Linux Kernel提权(50分)[2019年信息安全管理与评估
- linux – 生产服务器上的NodeJS – 权限
- linux – Varnish“FetchError no backend connection”错误
- linux – 如何在远程计算机上检查fsck结果,在启动时运行?
- linux – 如何从PHP cURL中记录传出的http请求?
- Linux 内核class_simple 接口