一直在做移动设备网络方面的开发,最近项目需要解决ios设备判断是否打开个人热点。
经过网上搜索,找到一个比较笨的办法,就是通过获取status bar高度是否等于40来判断热点状态。当有其他设备接入我的热点后,ios会在status bar height添加一行蓝底白色的文字提示有人接入,并一直保留在屏幕顶端,此时status bar height == 40。不过这个方法不能判断出在没有其他设备接入时,设备是否启动热点。
昨天,突然想到到获取ios设备ip地址的方法是遍历ios所有(实体/虚拟)网卡,当热点启动的时候,肯定会增加一个新的ip地址。于是通过日志记录了不启动热点和启动热点时所有ipv4地址,果然启动热点后,会增加一个桥接虚拟网卡,名称(ifa_name)为“bridge0”或“bridge100”。
以下为热点启动后,所有ipv4网卡的情况:
lo0 //本地ip, 127.0.0.1
en0 //局域网ip, 192.168.1.23
pdp_ip0 //WWAN地址,即3G ip,
bridge0 //桥接、热点ip,172.20.10.1
通过遍历所有ipv4网卡,查询网卡名称是否包含“bridge”即可判断当前热点是否启动。
01 | // Get All ipv4 interface |
02 | + (NSDictionary *)getIpAddresses { |
03 | NSMutableDictionary* addresses = [[NSMutableDictionary alloc] init]; |
04 | struct ifaddrs *interfaces = NULL; |
05 | struct ifaddrs *temp_addr = NULL; |
06 |
07 | @try { |
08 | // retrieve the current interfaces - returns 0 on success |
09 | NSInteger success = getifaddrs(&interfaces); |
10 | //NSLog(@"%@, success=%d", NSStringFromSelector(_cmd), success); |
11 | if (success == 0) { |
12 | // Loop through linked list of interfaces |
13 | temp_addr = interfaces; |
14 | while(temp_addr != NULL) { |
15 | if(temp_addr->ifa_addr->sa_family == AF_INET) { |
16 | // Get NSString from C String |
17 | NSString* ifaName = [NSString stringWithUTF8String:temp_addr->ifa_name]; |
18 | NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)]; |
19 | NSString* mask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_netmask)->sin_addr)]; |
20 | NSString* gateway = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_dstaddr)->sin_addr)]; |
21 | |
22 | |
23 | AXNetAddress* netAddress = [[AXNetAddress alloc] init]; |
24 | netAddress.name = ifaName; |
25 | netAddress.address = address; |
26 | netAddress.netmask = mask; |
27 | netAddress.gateway = gateway; |
28 | NSLog(@"netAddress=%@", netAddress); |
29 | addresses[ifaName] = netAddress; |
30 | } |
31 | temp_addr = temp_addr->ifa_next; |
32 | } |
33 | } |
34 | } |
35 | @catch (NSException *exception) { |
36 | NSLog(@"%@ Exception: %@", DEBUG_FUN, exception); |
37 | } |
38 | @finally { |
39 | // Free memory |
40 | freeifaddrs(interfaces); |
41 | } |
42 | return addresses; |
43 | } |
本文介绍了一种通过遍历iOS设备所有IPv4网卡来判断热点状态的方法,以及如何通过查询特定网卡名称来判断热点是否启动。同时提供了一个Swift代码片段用于实现这一功能。

2129

被折叠的 条评论
为什么被折叠?



