最近做一个校园网项目,其中有一个需求是获取到手机的mac地址,通过网关控制wifi联网.众所周知,苹果大大很操蛋,喜欢给我们码农找事情.ios7以后说是为了用户隐私不让获取mac地址.官方文档上这样写的:
"Twolow-level networking APIs that used to return a MAC address now return thefixed value 02:00:00:00:00:00. The APIs in question are sysctl(NET_RT_IFLIST) and ioctl(SIOCGIFCONF). Developers using the value of the MAC address should migrate toidentifiers such as -[UIDevice identifierForVendor].This change affects all apps running on iOS 7”。
所以在iOS7以后想要获取设备的唯一标示Mac地址已经不行了,只能用其他的代替。
经过和后台商量,决定用http协议,状态码是302 拦截重定向url获取到手机的mac地址.
原理是这样的 :当连上我们公司的ssid,启动app时向外面发送一个请求,此时我们的ap会收到这个请求之后,返回一个重定向的url给我们.值得一提的是,ap能获取到我们手机的mac地址,那么通过ap返回一个重定向的url,里面拼接了一个mac地址,我们截取这个mac地址就可以了.
对了 需要在项目中配置plist文件 App Transport Security Settings的Allow Arbitrary Loads为YES,不然返回的状态码一直都是0
废话 不多说,上代码...
通过NSURLSession
方法
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,NSURLSessionDelegate,NSURLSessionTaskDelegate>
@end
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake(50, 150, 150, 38);
[button addTarget:self action:@selector(getMac) forControlEvents:(UIControlEventTouchUpInside)];
[button setTitle:@"获取mac地址" forState:(UIControlStateNormal)];
[button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
[self.view addSubview:button];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)getMac{
[self getMacfor];
}
-(void)getMacfor{
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
//NSMutableURLRequest *quest = [NSMutableURLRequest requestWithURL:url];
NSMutableURLRequest *quest = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:3];
// quest.HTTPMethod = @"GET";
// NSURLConnection *connect = [NSURLConnection connectionWithRequest:quest delegate:self];
// [connect start];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue currentQueue]];
NSURLSessionDataTask *task = [urlSession dataTaskWithRequest:quest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSLog(@"状态码是 %ld",urlResponse.statusCode);
NSLog(@"allheaderfields-- %@",urlResponse.allHeaderFields);
NSDictionary *dic = urlResponse.allHeaderFields;
NSLog(@"哈哈%@",dic[@"Location"]);
NSString *location = dic[@"Location"];
long range = [location rangeOfString:@"&mac"].location;
if (range==NSNotFound) {
NSLog(@"没有找到");
[self ShowAlert:@"没有获取到"];
}else {
NSLog(@"%ld",range);
NSLog(@"%@",[location substringWithRange:NSMakeRange(range+5, 17)]);
}
//http://60.190.139.244:9080/cmps/admin.php/api/login/?gw_address=192.168.51.1&gw_port=2060&gw_id=00037F0064DC&ip=192.168.51.113&mac=48:e9:f1:b7:01:1b
[self ShowAlert:[location substringWithRange:NSMakeRange(range+5, 17)]];
}];
[task resume];
}
//返回重定向页面
-(void)ShowAlert:(NSString *)str{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alert show];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler{
completionHandler(nil);
}
这个获取方法还是蛮有局限性的,需要配置对应的ap,只有添加了重定向的url才能获取的到.不过笔者公司完全可以配置这个了!
附 ios7.0之前获取方法
导入头文件
<sys/sysctl.h>
<net/if.h>
<net/if_dl.h>
- (NSString *) macaddress
{
int mib[6];
size_t len;
char *buf;
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 NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1/n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!/n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
// NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
NSLog(@"outString:%@", outstring);
free(buf);
return [outstring uppercaseString];
}
最后推荐一个技术交流群,里面大神很多! 529043462