美文网首页
iOS 获取外网ip地址

iOS 获取外网ip地址

作者: 春阳_fc96 | 来源:发表于2019-05-07 14:23 被阅读0次

    - (void)getIp

    {

        NSLog(@"开始获取ip");

        NSError*error;

        NSString*ip =@"";

        // 方法1    不稳定,有时太慢,有时得不到结果

        NSURL *url = [NSURL URLWithString:@"https://ifconfig.me/ip"];

        ip = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

        // 方法2

        NSURL *url = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];

        NSString *response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

        NSDictionary*dicResponse = [responsemj_JSONObject];

        if(dicResponse && dicResponse[@"data"]) {

            NSDictionary*dicData = dicResponse[@"data"];

            if(dicData && dicData[@"ip"]) {

                ip = dicData[@"ip"];

            }

        }

        // 方法3 

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

        NSString*response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

        //判断返回字符串是否为所需数据

        NSString *prefix = @"var returnCitySN = ";

        if([responsehasPrefix:prefix]) {

            // 删除多余内容

            response = [responsesubstringFromIndex:prefix.length];

            response = [responsesubstringToIndex:response.length-1];

            NSDictionary*dicResponse = [responsemj_JSONObject];

            if(dicResponse && dicResponse[@"cip"]) {

                ip = dicResponse[@"cip"];

            }

        }

        NSLog(@"当前网络ip %@", ip);

    }

    相关文章

      网友评论

          本文标题:iOS 获取外网ip地址

          本文链接:https://www.haomeiwen.com/subject/ivmeoqtx.html