使用网络上的方法,在 大于 ios 7 的环境下, 永远返回的MAC 为 02:00:00:00:00:00 下面说下我获取的MAC的思路,在连接wifi 的情况下,通过 wifi(读取ARP),获取当前设备的IP。
+ (nonnull NSString *)currentIPAddressOf: (nonnull NSString *)device {
struct ifaddrs *addrs;
NSString *ipAddress = nil;
if(getifaddrs(&addrs) != 0) {
return nil;
}//end if
//get ipv4 address
for(struct ifaddrs *addr = addrs ; addr ; addr = addr->ifa_next) {
if(!strcmp(addr->ifa_name, [device UTF8String])) {
if(addr->ifa_addr) {
struct sockaddr_in *in_addr = (struct sockaddr_in *)addr->ifa_addr;
if(in_addr->sin_family == AF_INET) {
ipAddress = [Address IPv4Ntop:in_addr->sin_addr.s_addr];
break;
}//end if
}//end if
}//end if
}//end
freeifaddrs(addrs);
return ipAddress;
}//end currentIPAddressOf:
+ (nullable NSString *)IPv4Ntop: (in_addr_t)addr {
char buffer[INET_ADDRSTRLEN] = {0};
return inet_ntop(AF_INET, &addr, buffer, sizeof(buffer)) ? [NSString stringWithUTF8String:buffer] : nil;
}//end IPv4Ntop:将数值格式转化为点分的十进制ip地址格式
然后发送mDNS组播"_apple -mobdev2. _tcp.local" 查询PTR记录。
unsigned char response[NS_PACKETSZ];
int len;
//send mdns query
if((len = res_query(QUERY_NAME, ns_c_in, ns_t_ptr, response, sizeof(response))) < 0) {
fprintf(stderr, "res_search(): %s\n", hstrerror(h_errno));
return nil;
}//end if
从Respond 中解析MAC地址;
//parse mdns message
ns_msg handle;
if(ns_initparse(response, len, &handle) < 0) {
fprintf(stderr, "ns_initparse(): %s\n", hstrerror(h_errno));
return nil;
}//end if
//get answer length
len = ns_msg_count(handle, ns_s_an);
if(len < 0) {
fprintf(stderr, "ns_msg_count return zero\n");
return nil;
}//end if
//try to get mac address from data
NSString *macAddress = nil;
for(int i = 0 ; i < len ; i++) {
ns_rr rr;
ns_parserr(&handle, ns_s_an, 0, &rr);
if(ns_rr_class(rr) == ns_c_in &&
ns_rr_type(rr) == ns_t_ptr &&
!strcmp(ns_rr_name(rr), QUERY_NAME)) {
char *ptr = (char *)(ns_rr_rdata(rr) + 1);
int l = (int)strcspn(ptr, "@");
char *tmp = calloc(l + 1, sizeof(char));
if(!tmp) {
perror("calloc()");
continue;
}//end if
memcpy(tmp, ptr, l);
macAddress = [NSString stringWithUTF8String:tmp];
free(tmp);
}//end if
}//end for each
return macAddress;
网友评论