ios下獲取所有實(shí)體/虛擬網(wǎng)卡的信息,并以此判斷設(shè)備所處的網(wǎng)絡(luò)狀態(tài)

1.手機(jī)發(fā)射WiFi熱點(diǎn)
獲取ios設(shè)備ip地址的方法是遍歷ios所有(實(shí)體/虛擬)網(wǎng)卡,當(dāng)熱點(diǎn)啟動(dòng)的時(shí)候,肯定會(huì)增加一個(gè)新的ip地址。于是通過(guò)日志記錄了不啟動(dòng)熱點(diǎn)和啟動(dòng)熱點(diǎn)時(shí)所有ipv4地址,果然啟動(dòng)熱點(diǎn)后,會(huì)增加一個(gè)橋接虛擬網(wǎng)卡,名稱(ifa_name)為“bridge0”或“bridge100”

以下為熱點(diǎn)啟動(dòng)后,所有ipv4網(wǎng)卡的情況:

  • lo0 //本地ip, 127.0.0.1
  • en0 //局域網(wǎng)ip, 192.168.1.23
  • pdp_ip0 //WWAN地址,即3G ip,
  • bridge0 //橋接、熱點(diǎn)ip,172.20.10.1

通過(guò)遍歷所有ipv4網(wǎng)卡,查詢網(wǎng)卡名稱是否包含“bridge”即可判斷當(dāng)前熱點(diǎn)是否啟動(dòng)。

// 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;
}

http://blog.csdn.net/qq_15509071/article/details/54632811

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容