获取Mac地址(fit for iOS,os x)

本文提供了一段使用C语言获取Mac地址的代码示例,通过系统调用和内存操作实现了从内核中获取Mac地址的过程,并最终将获取到的地址格式化为传统格式的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

+ (NSString *)getMacAddress

{

    int                 mgmtInfoBase[6];

    char                *msgBuffer = NULL;

    size_t              length;

    unsigned char       macAddress[6];

    struct if_msghdr    *interfaceMsgStruct;

    struct sockaddr_dl  *socketStruct;

    NSString            *errorFlag = NULL;

    

    // Setup the management Information Base (mib)

    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem

    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info

    mgmtInfoBase[2] = 0;

    mgmtInfoBase[3] = AF_LINK;        // Request link layer information

    mgmtInfoBase[4] = NET_RT_IFLIST// Request all configured interfaces

    

    // With all configured interfaces requested, get handle index

    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)

        errorFlag = @"if_nametoindex failure";

    else

    {

        // Get the size of the data available (store in len)

        if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)

            errorFlag = @"sysctl mgmtInfoBase failure";

        else

        {

            // Alloc memory based on above call

            if ((msgBuffer = malloc(length)) == NULL)

                errorFlag = @"buffer allocation failure";

            else

            {

                // Get system information, store in buffer

                if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)

                    errorFlag = @"sysctl msgBuffer failure";

            }

        }

    }

    

    // Befor going any further...

    if (errorFlag != NULL)

    {

        NSLog(@"Error: %@", errorFlag);

        return errorFlag;

    }

    

    // Map msgbuffer to interface message structure

    interfaceMsgStruct = (struct if_msghdr *) msgBuffer;

    

    // Map to link-level socket structure

    socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);

    

    // Copy link layer address data in socket structure to an array

    memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);

    

    // Read from char array into a string object, into traditional Mac address format

    NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",

                                  macAddress[0], macAddress[1], macAddress[2],

                                  macAddress[3], macAddress[4], macAddress[5]];

    

    

    // Release the buffer memory

    free(msgBuffer);

   

    return macAddressString;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值