一、获取手机外网IP(公网IP)
网上找了很久获取外网IP的方法,很多访问网址已经不能用了,能用的主要有2个,但是获取到的IP地址不同,下面详细介绍。
首推方法1:此方法采用的淘宝网址,获取的到IP与百度IP是一样的,考虑到如今百度横行,所以我使用的是此方法。
[objc]view plaincopy-(NSString*)deviceWANIPAddress { NSURL*ipURL=[NSURLURLWithString:@"/service/getIpInfo.php?ip=myip"]; NSData*data=[NSDatadataWithContentsOfURL:ipURL]; NSDictionary*ipDic=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror: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 plaincopy-(NSString*)getWANIPAddress { NSError*error; NSURL*ipURL=[NSURLURLWithString:@"/cityjson?ie=utf-8"]; NSMutableString*ip=[NSMutableStringstringWithContentsOfURL:ipURLencoding:NSUTF8StringEncodingerror:&error]; //判断返回字符串是否为所需数据 if([iphasPrefix:@"varreturnCitySN="]){ //对字符串进行处理,然后进行json解析 //删除字符串多余字符串 NSRangerange=NSMakeRange(0,19); [ipdeleteCharactersInRange:range]; NSString*nowIp=[ipsubstringToIndex:ip.length-1]; //将字符串转换成二进制进行Json解析 NSData*data=[nowIpdataUsingEncoding:NSUTF8StringEncoding]; NSDictionary*dict=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil]; NSLog(@"%@",dict); returndict[@"cip"]?dict[@"cip"]:@""; } return@""; }
访问接口取到的数据:
参考:/henry_moneybag/article/details/51463375
还有一个接口可直接获取到IP,但返回比较慢,可能返回失败,不推荐。
[objc]view plaincopyNSError*error; NSURL*ipURL=[NSURLURLWithString:@"http://ifconfig.me/ip"]; NSString*ip=[NSStringstringWithContentsOfURL:ipURLencoding:NSUTF8StringEncodingerror:&error];