OS X(C)接口的MAC地址 [英] MAC address from interface on OS X (C)

查看:164
本文介绍了OS X(C)接口的MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This might be a stupid question and I apologize if it's already been addressed here, but I've searched quite a bit without much luck. I'm trying to get my interface's hardware address in C and I'm using OS X (x86-64). I know how to get it with ifconfig, but I want my program to get it automatically for any computer, well, at least OS X computers. I found another thread that posted this link which pretty much does what I want (with some modifications), but I can't make the iokit functions link in ld (my compiler is gcc). I tried adding the flags -lIOKit and -framework IOKit to the gcc command line, but I still get the same link errors. Here's a link to my code: header and source.

推荐答案

这个小程序无需更改OSX即可使用。

This little program will work without changes on OSX.

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

Code : (credits to Alecs King from freebsd list)

#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;

这篇关于OS X(C)接口的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆