一、获取手机外网IP(公网IP)
网上找了很久获取外网IP的方法,很多访问网址已经不能用了,能用的主要有2个,但是获取到的IP地址不同,下面详细介绍。
首推方法1:此方法采用的淘宝网址,获取的到IP与百度IP是一样的,考虑到如今百度横行,所以我使用的是此方法。
[objc] view plain copy -(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]; NSInteger code = [ipDic objectForKey:@'code']; if (code == 0) { //成功了 return (ipDic[@"data"][@"ip"] ? ipDic[@"data"][@"ip"] : @""); } else if (code == 1) { //失败了 return @""; } }
访问接口成功返回的json数据:
访问接口失败返回的json数据(附截图):
{
"code":1,
"date":"ip info not found"
}
百度ip查到的本机ip:
方法2:此方法访问的搜狐的获取ip接口,返回的IP与百度淘宝不一样。(可能是此接口精确到了具体的区。。。)
[objc] view plain copy -(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,但返回比较慢,可能返回失败,不推荐。
[objc] view plain copy NSError *error; NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"]; NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];