ios获取手机外网IP(公网IP)获得所在城市和地区

#import <sys/socket.h>

#import <sys/sockio.h>

#import <sys/ioctl.h>

#import <net/if.h>

#import <arpa/inet.h>

 

网上找了很久获取外网IP的方法,很多访问网址已经不能用了,能用的主要有2个,但是获取到的IP地址不同,下面详细介绍。

首推方法1:此方法采用的淘宝网址,获取的到IP与百度IP是一样的,考虑到如今百度横行,所以我使用的是此方法。

-(NSString *)deviceWANIPAddress

{

    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];

    NSString *ipStr = nil;

    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功

        ipStr = ipDic[@"data"][@"ip"];

    }

    return (ipStr ? ipStr : @"");

}

访问接口返回的json数据

百度ip查到的本机ip:

方法2:此方法访问的搜狐的获取ip接口,返回的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"] : @"";

    }

    return @"";

}

参考:http://blog.csdn.net/henry_moneybag/article/details/51463375

还有一个接口可直接获取到IP,但返回比较慢,可能返回失败,不推荐。

NSError *error;

NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];

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

 

参考:https://blog.csdn.net/txz_gray/article/details/53217293

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值