#include <arpa/inet.h>#include <netdb.h>#include <net/if.h>#include <ifaddrs.h>#import <dlfcn.h>/* 一直在做移動設備網絡方面的開發,最近項目需要解決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 */// 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)]; if ([ifaName isEqualToString:@"pdp_ip0"]) { [addresses setObject:address forKey:@"address"]; } NSLog(@"ifaName = %@,address= %@, mask= %@, gateway = %@",ifaName,address,mask,gateway); } temp_addr = temp_addr->ifa_next; } } } @catch (NSException *exception) { } @finally { // Free memory freeifaddrs(interfaces); } return addresses;}
新聞熱點
疑難解答