在macOS应用中通过Objective-C获取网络接口收发字节统计的技术问询
搞定macOS网络接口收发字节统计的靠谱方案
兄弟,我太懂你这种找不到方法的抓狂了!之前我也在Objective-C里折腾了好久才摸清楚门道,给你分享个直接能用的方案:
用系统原生API getifaddrs 直接拿数据
macOS其实早就给我们留了口子——getifaddrs函数能枚举所有网络接口,每个接口的统计数据就藏在if_data结构体里,直接就能拿到累计接收和发送的字节数,完全不用绕命令行的弯路。
直接能用的Objective-C代码
#include <ifaddrs.h> #include <net/if.h> #include <netinet/in.h> - (void)fetchNetworkInterfaceStats { struct ifaddrs *interfaceList = NULL; struct ifaddrs *currentInterface = NULL; int result = getifaddrs(&interfaceList); if (result == 0) { currentInterface = interfaceList; while (currentInterface != NULL) { // 只处理链路层接口(比如Wi-Fi、以太网这些实际收发数据的接口) if (currentInterface->ifa_addr->sa_family == AF_LINK) { struct if_data *interfaceData = (struct if_data *)currentInterface->ifa_data; NSString *interfaceName = [NSString stringWithUTF8String:currentInterface->ifa_name]; uint64_t totalReceived = interfaceData->ifi_ibytes; uint64_t totalSent = interfaceData->ifi_obytes; NSLog(@"接口 %@: 累计收%llu字节,累计发%llu字节", interfaceName, totalReceived, totalSent); } currentInterface = currentInterface->ifa_next; } } // 别忘了释放资源,避免内存泄漏 freeifaddrs(interfaceList); }
为啥你之前的方法走不通?
- sysctl:它返回的大多是全局网络统计,比如所有TCP连接的总数据,没法精准对应到单个网卡
- nettop:这货的CLI输出带了一堆终端控制字符(用来动态刷新界面的),
grep根本没法正常解析,就算用nettop -L导出机器可读格式,解析起来也比直接用API麻烦多了 - App Store里的应用:它们底层其实也是调用了类似的系统API,但都是封装好的,没法满足自定义需求
额外需求:实时监控带宽?
如果想算每秒的带宽速率,就每隔1秒调用一次上面的方法,把两次的字节数相减,除以时间差(1秒)就是当前的速率了,简单得很。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

