OS X(C)接口的MAC地址

这可能是一个愚蠢的问题,如果它已经在这里得到解决,我道歉,但我搜索了一下,没有太多运气。 我正在尝试用C语言获取接口的硬件地址,而我正在使用OS X(x86-64)。 我知道如何使用ifconfig ,但我希望我的程序能够自动获取任何计算机,至少OS X计算机。 我发现另一个post发布了这个链接 ,它几乎可以做我想要的(有一些修改),但是我不能在ld创建iokit函数链接(我的编译器是gcc )。 我尝试将标志-lIOKit-framework IOKitgcc命令行,但我仍然得到相同的链接错误。 这是我的代码的链接: 标题和来源 。

这个小程序无需更改OSX即可运行。

代码:(从freebsd列表中归功于Alecs King)

 #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  int main(int argc, char *argv[]) { int mib[6], len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; if (argc != 2) { fprintf(stderr, "Usage: getmac \n"); return 1; } mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex(argv[1])) == 0) { perror("if_nametoindex error"); exit(2); } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { perror("sysctl 1 error"); exit(3); } if ((buf = malloc(len)) == NULL) { perror("malloc error"); exit(4); } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { perror("sysctl 2 error"); exit(5); } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); printf("%02x:%02x:%02x:%02x:%02x:%02x\n", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)); return 0; } 

但是,你应该改变int len; to size_t len;