1.獲取設備外網IP,根據淘寶網獲取,其結果與百度搜IP所獲得的結果相同。其方法為:
- (NSString *)GetIPAdderss{
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];
return (ipDic[@"data"][@"ip"]?ipDic[@"data"][@"ip"]:@"0.0.0.0");
}
其獲取結果為:

image.png
2.根據搜狐網獲取外網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"]:@"0.0.0.0";
}
return @"0.0.0.0";
}
其結果為:

image.png