一直在做移动设备网络方面的开发,最近项目需要解决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”即可判断当前热点是否启动。
// Get All ipv4 interface
+ (NSDictionary *)getIpAddresses {
NSMutableDictionary* addresses = [[NSMutableDictionary alloc] init];
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
@try {
// retrieve the current interfaces - returns 0 on success
NSInteger success = getifaddrs(&interfaces);
//NSLog(@"%@, success=%d", NSStringFromSelector(_cmd), success);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Get NSString from C String
NSString* ifaName = [NSString stringWithUTF8String:temp_addr->ifa_name];
NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)];
NSString* mask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_netmask)->sin_addr)];
NSString* gateway = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_dstaddr)->sin_addr)];
AXNetAddress* netAddress = [[AXNetAddress alloc] init];
netAddress.name = ifaName;
netAddress.address = address;
netAddress.netmask = mask;
netAddress.gateway = gateway;
NSLog(@"netAddress=%@", netAddress);
addresses[ifaName] = netAddress;
}
temp_addr = temp_addr->ifa_next;
}
}
}
@catch (NSException *exception) {
NSLog(@"%@ Exception: %@", DEBUG_FUN, exception);
}
@finally {
// Free memory
freeifaddrs(interfaces);
}
return addresses;
}
来源:oschina
链接:https://my.oschina.net/u/211651/blog/169439