ios下获取所有实体/虚拟网卡的信息,并以此判断设备所处的网络状态

1.手机发射WiFi热点
获取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;
}

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

你可能感兴趣的:(ios下获取所有实体/虚拟网卡的信息,并以此判断设备所处的网络状态)