#include <stdio.h>
#include <stdlib.h>
#include <sys/sysctl.h>
int main(int argc, const char * argv[]) {
int mib[6];
size_t len;
char *buf;
char *next;
u_int64_t totalibytes;
u_int64_t totalobytes;
int pid;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0;
mib[3] = AF_INET;
mib[4] = NET_RT_IFLIST2;
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
perror("sysctl");
exit(1);
}
if ((buf = malloc(len)) == NULL) {
perror("malloc");
exit(1);
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
perror("sysctl");
exit(1);
}
next = buf;
while (next < buf + len) {
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 incoming bytes: %llu\n", totalobytes);
printf("Total outgoing bytes: %llu\n", totalibytes);
free(buf);
return 0;
}
c语言获取mac电脑各应用流量情况的代码
最新推荐文章于 2023-08-16 15:59:39 发布
该程序使用C语言和sysctl函数获取PF_ROUTE协议族下AF_INET接口的输入(totalibytes)和输出(totalobytes)字节数,通过遍历结构体获取多个接口的信息,并打印总字节数。
摘要由CSDN通过智能技术生成