获取当前设备的局域网以及链接的WiFi分配的IP地址

#pragma mark - 获取设备当前连接的局域网的名称(获取不到返回nil)
/**
 *  @author zm
 *
 *  @brief  获取设备当前连接的局域网的名称(获取不到返回nil)
 *
 *  @return 局域网的名称
 */
- (NSString *)f_getCurrentWifiSSID
{
    NSArray *ifs = (__bridgeid)CNCopySupportedInterfaces();
    id info =nil;
    NSString *ssid =nil;
    for (NSString *ifnamin ifs) {
        info = (__bridgeid)CNCopyCurrentNetworkInfo((__bridgeCFStringRef)ifnam);
        if (info && [infocount]) {
            break;
        }
    }
    
    NSDictionary *dctySSID = (NSDictionary *)info;
    if(dctySSID)
    {
        ssid = [dctySSIDobjectForKey:@"SSID"];
    }
    return ssid;
}

#pragma mark - 获取设备当前连接的wifi所分配的IP地址(获取不到返回nil)
/**
 *  @author zm
 *
 *  @brief 获取设备当前连接的wifi所分配的IP地址(获取不到返回nil)
 *
 *  @return wifi分配的IP地址
 */
-(NSString *)f_getCurrentWifiIP
{
    NSString *_str_address =nil;
    structifaddrs *_struct_interfaces = NULL;
    structifaddrs *_struct_temp_addr = NULL;
    int int_success =0;
    int_success = getifaddrs(&_struct_interfaces);

    if (int_success ==0) { // 0表示获取成功
        _struct_temp_addr = _struct_interfaces;
        while (_struct_temp_addr !=NULL) {
            if( _struct_temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSStringstringWithUTF8String:_struct_temp_addr->ifa_name]isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    _str_address = [NSStringstringWithUTF8String:inet_ntoa(((structsockaddr_in *)_struct_temp_addr->ifa_addr)->sin_addr)];
                }
            }
            _struct_temp_addr = _struct_temp_addr->ifa_next;
        }
    }
    freeifaddrs(_struct_interfaces);
    return _str_address;
}


你可能感兴趣的:(局域网IP地址)