一直在作移動設備網絡方面的開發,最近項目須要解決ios設備判斷是否打開我的熱點。ios
通過網上搜索,找到一個比較笨的辦法,就是經過獲取status bar高度是否等於40來判斷熱點狀態。當有其餘設備接入個人熱點後,ios會在status bar height添加一行藍底白色的文字提示有人接入,並一直保留在屏幕頂端,此時status bar height == 40。不過這個方法不能判斷出在沒有其餘設備接入時,設備是否啓動熱點。網絡
昨天,忽然想到到獲取ios設備ip地址的方法是遍歷ios全部(實體/虛擬)網卡,當熱點啓動的時候,確定會增長一個新的ip地址。因而經過日誌記錄了不啓動熱點和啓動熱點時全部ipv4地址,果真啓動熱點後,會增長一個橋接虛擬網卡,名稱(ifa_name)爲「bridge0」或「bridge100」。 oop
如下爲熱點啓動後,全部ipv4網卡的狀況:spa
lo0 //本地ip, 127.0.0.1
en0 //局域網ip, 192.168.1.23
pdp_ip0 //WWAN地址,即3G ip,
bridge0 //橋接、熱點ip,172.20.10.1.net
經過遍歷全部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; }