在Mac|在Mac OSX中获取网卡MAC地址

今天在CocoaChina上看到有人发帖在询问如何在Mac OSX下获得网卡的物理地址,恰好最近在学习IOKit的一些知识,所以通过IOKit的接口肯定是可以很方便的拿到MAC地址信息的,但不知道还有没有其它更方便的API了,所以我姑且贴出一段通过IOKit去获得网卡MAC地址的代码:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { kern_return_t kr; CFMutableDictionaryRef matchDict; io_iterator_t iterator; io_registry_entry_t entry; matchDict = IOServiceMatching("IOEthernetInterface"); kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchDict, &iterator); NSDictionary *resultInfo = nil; while ((entry = IOIteratorNext(iterator)) != 0) { CFMutableDictionaryRef properties=NULL; kr = IORegistryEntryCreateCFProperties(entry, &properties, kCFAllocatorDefault, kNilOptions); if (properties) { resultInfo = (__bridge_transfer NSDictionary *)properties; NSString *bsdName = [resultInfo objectForKey:@"BSD Name"]; NSData *macData = https://www.it610.com/article/[resultInfo objectForKey:@"IOMACAddress"]; if (!macData) { continue; }NSMutableString *macAddress = [[NSMutableString alloc] init]; const UInt8 *bytes = [macData bytes]; for (int i=0; i

【在Mac|在Mac OSX中获取网卡MAC地址】同时可以通过iOS 获取网卡地址的方式获取网卡地址
+ (NSString *)currentMACAddress { char addr[64]; intmib[6]; size_tlen; charbuf[1024]; unsigned char*ptr; struct if_msghdr*ifm; struct sockaddr_dl*sdl; 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("en0")) == 0) { printf("Error: if_nametoindex error/n"); return FALSE; }if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1/n"); return FALSE; }if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return FALSE; }ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); sprintf(addr, "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)); NSString *macAddress = [[NSString alloc] initWithCString:addr encoding:NSASCIIStringEncoding]; return macAddress; }

    推荐阅读