在OS X操作系统中获取接口的MAC地址 (C语言)

8

这可能是一个愚蠢的问题,如果已经在这里解决了,我很抱歉,但我搜索了很多没有什么运气。我正在尝试在C语言中获取我的接口硬件地址,并且我正在使用OS X(x86-64)。我知道如何使用ifconfig获取它,但我希望我的程序可以自动获取任何计算机的地址,至少是OS X计算机。我找到了另一个线程,发布了这个链接,基本上做到了我想要的(进行了一些修改),但我无法使iokit函数在ld中链接(我的编译器是gcc)。我尝试将标志-lIOKit-framework IOKit添加到gcc命令行中,但我仍然得到相同的链接错误。这里是我的代码链接:头文件源代码


我一直以为巴甫洛夫有一只狗...不是吗? - user405725
1
是的,我的名字只是一个文字游戏。 - Pavlov's Kitten
1个回答

8

这个小程序在OSX上可以直接使用,无需更改。

代码:(感谢来自freebsd列表的Alecs King)

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

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 <interface>\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;更改为size_t len;


谢谢,这正是我想要的。 - Pavlov's Kitten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接