一直在做移動設備網絡方面的開發,最近項目需要解決ios設備判斷是否打開個人熱點。
http://www.cnblogs.com/gaoxiaoniu/p/5482623.html
經過網上搜索,找到一個比較笨的辦法,就是通過獲取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