获取设备IP地址

1.获取设备外网IP,根据淘宝网获取,其结果与百度搜IP所获得的结果相同。其方法为:

- (NSString *)GetIPAdderss{
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return (ipDic[@"data"][@"ip"]?ipDic[@"data"][@"ip"]:@"0.0.0.0");
}

其获取结果为:


image.png

2.根据搜狐网获取外网IP地址,其方法为:

- (NSString *)getWANIPAddress{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
    NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
    //判断返回字符串是否为所需数据
    if ([ip hasPrefix:@"var returnCitySN = "]) {
        //对字符串进行处理,然后进行json解析
        //删除多余字符串
        NSRange range = NSMakeRange(0, 19);
        [ip deleteCharactersInRange:range];
        NSString *nowip = [ip substringToIndex:ip.length-1];
        //将字符串转换成二进制进行Json解析
        NSData *data = [nowip dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        return dict[@"cip"]?dict[@"cip"]:@"0.0.0.0";
    }
    return @"0.0.0.0";
}

其结果为:


image.png

你可能感兴趣的:(获取设备IP地址)