iOS 获取Mac Address

#import <net/if.h>
#import <sys/sysctl.h>
#import <net/if_dl.h>

- (NSString *)macAddress
{
    int  temp[6]={0};
    size_t len=0;
    char *buf=NULL;
    unsigned char *laddr=NULL;
    struct if_msghdr *ifmsghdr=NULL;
    struct sockaddr_dl *sockaddr=NULL;
    
    temp[0] = CTL_NET;
    temp[1] = AF_ROUTE;
    temp[2] = 0;
    temp[3] = AF_LINK;
    temp[4] = NET_RT_IFLIST;
    
    temp[5] = if_nametoindex("en0");
    if (0 == temp[5])
    {
        return nil;
    }
    
    if (sysctl(temp, 6, NULL, &len, NULL, 0) < 0)
    {
        return nil;
    }
    
    buf = malloc(len+32);
    if (buf == NULL)
    {
        return nil;
    }
    
    if (sysctl(temp, 6, buf, &len, NULL, 0) < 0)
    {
        free(buf);
        
        return nil;
    }
    
    ifmsghdr = (struct if_msghdr *)buf;
    sockaddr = (struct sockaddr_dl *)(ifmsghdr + 1);
    laddr = (unsigned char *)LLADDR(sockaddr);

    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *laddr, *(laddr+1), *(laddr+2), *(laddr+3), *(laddr+4), *(laddr+5)];
    free(buf);
    
    return [outstring uppercaseString];
}






你可能感兴趣的:(ios)