How can I programmatically get the MAC address of an iphone

后端 未结 12 2027
春和景丽
春和景丽 2020-11-22 08:06

How to programmatically get an iPhone\'s MAC address and IP address?

12条回答
  •  礼貌的吻别
    2020-11-22 08:41

    #import 
    #import 
    #import 
    #import 
    #define IFT_ETHER 0x6
    

    ...

    - (NSString*)macAddress
    {
        NSString* result = nil;
    
        char* macAddressString = (char*)malloc(18);
        if (macAddressString != NULL)
        {
            strcpy(macAddressString, "");
    
            struct ifaddrs* addrs = NULL;
            struct ifaddrs* cursor;
    
            if (getifaddrs(&addrs) == 0)
            {
                cursor = addrs;
    
                while (cursor != NULL)
                {
                    if ((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl*)cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp("en0", cursor->ifa_name) == 0)
                    {
                        const struct sockaddr_dl* dlAddr = (const struct sockaddr_dl*) cursor->ifa_addr;
                        const unsigned char* base = (const unsigned char*)&dlAddr->sdl_data[dlAddr->sdl_nlen];
    
                        for (NSInteger index = 0; index < dlAddr->sdl_alen; index++)
                        {
                            char partialAddr[3];
    
                            sprintf(partialAddr, "%02X", base[index]);
                            strcat(macAddressString, partialAddr);
                        }
                    }
    
                    cursor = cursor->ifa_next;
                }
    
            }
    
            result = [[[NSString alloc] initWithUTF8String:macAddressString] autorelease];
    
            free(macAddressString);
        }
    
        return result;
    }
    

提交回复
热议问题