IOS获取外网IP和外网ip地址的方法

原文链接:https://www.jianshu.com/p/2a1a567bbb6e


-(NSString *)getWANIP{

    NSError *error;

    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];

     NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];

    NSLog(@"%@",ip);

    //判断返回字符串是否为所需数据
    if ([ip hasPrefix:@"var returnCitySN = "]) {

         //删除字符串多余字符串
        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"] : @"";
    }

    return @"";
}

你可能感兴趣的:(IOS获取外网IP和外网ip地址的方法)