最近有发现公司很多设备采集的mac地址都有空或则000000002,000000000等这种地址,明显不是正常的mac地址,特意去调研了一下相关原因, 目前获取设备mac地址的相关方案有两种,一种C语言类型,一种OC语言类型。具体如下:
方案一
代码类型:C语言
逻辑:通过遍历网络接口列表获取获取mac地址指针从而获取地址,取返回数组列表首个。
缺点:所用方法已被iOS系统屏蔽,获取到的均为不准确和重复地址。
关键方法:
getifaddrs
LLADDR
返回示例:
Interface: lo0
MAC Address: 00:00:00:00:00:00
Interface: XHC0
MAC Address: 00:00:00:00:00:00
Interface: pdp_ip0
MAC Address: 00:00:00:00:00:00
Interface: pdp_ip5
MAC Address: 00:00:00:00:00:FF
Interface: pdp_ip1
MAC Address: 00:00:00:00:00:FF
Interface: pdp_ip2
MAC Address: 00:00:00:00:00:FF
Interface: pdp_ip4
MAC Address: 00:00:00:00:00:FF
Interface: pdp_ip3
MAC Address: 00:00:00:00:00:01
Interface: anpi0
MAC Address: 02:00:00:00:00:00
Interface: en1
MAC Address: 02:00:00:00:00:00
Interface: en2
MAC Address: 02:00:00:00:00:00
Interface: utun0
MAC Address: 00:00:00:00:00:00
Interface: ap1
MAC Address: 02:00:00:00:00:00
Interface: en0
MAC Address: 02:00:00:00:00:00
Interface: awdl0
MAC Address: 02:00:00:00:00:00
Interface: llw0
MAC Address: 02:00:00:00:00:00
Interface: ipsec0
MAC Address: 00:00:00:00:00:00
Interface: utun1
MAC Address: 00:00:00:00:00:00
Interface: utun2
MAC Address: 00:00:00:00:00:00
Interface: utun3
MAC Address: 00:00:00:00:00:00
Interface: ipsec1
MAC Address: 00:00:00:00:00:00
Interface: utun4
MAC Address: 00:00:00:00:00:00
Interface: ipsec6
MAC Address: 00:00:00:00:00:00
Interface: ipsec7
MAC Address: 00:00:00:00:00:00
Interface: ipsec2
MAC Address: 00:00:00:00:00:00
Interface: ipsec3
MAC Address: 00:00:00:00:00:00
代码示例:
struct ifaddrs *ifap, *ifa;
unsigned char *mac;
// 获取系统网络接口列表
if (getifaddrs(&ifap) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
// 遍历网络接口列表,获取MAC地址
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family == AF_LINK) {
// 获取MAC地址指针
mac = reinterpret_cast<unsigned char *>(LLADDR((struct sockaddr_dl *)ifa->ifa_addr));
// 打印网卡名和MAC地址
printf("Interface: %s\n", ifa->ifa_name);
printf("MAC Address: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
}
// 释放网络接口列表
freeifaddrs(ifap);
方案二:
代码类型:OC语言
逻辑:遍历网络接口列表获取当前网络信息从而获取BSSID,取返回数据列表首个。
缺点:无wifi证书权限情况下所有iOS设备获取都为空。
关键方法:
CNCopySupportedInterfaces
CNCopyCurrentNetworkInfo
返回示例:
en0
Printing description of info:
{
BSSID = "bc:d0:eb:8:52:40";
SSID = XCSC;
SSIDDATA = {length = 4, bytes = 0x58435343};
}
代码示例:
id info = nil;
#if TARGET_OS_IOS
NSArray* ifs = CFBridgingRelease(CNCopySupportedInterfaces());
for (NSString* ifname in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef)ifname);
if (info && [info count]) {
break;
}
}
#else
#endif
NSDictionary* dic = (NSDictionary*)info;
NSString* bssid = [dic objectForKey:@"BSSID"];
return bssid ? bssid : @"";