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

    xiaoxiao2022-07-12  197

    #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)