IOS 获取IP地址

Posted Somebody

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS 获取IP地址相关的知识,希望对你有一定的参考价值。

获取内网IP地址

//获取ip地址
+(NSString *)getIPaddress
{
   //获取内网IP
   NSString *address = @"error";
   struct ifaddrs * ifaddress = NULL;
   struct ifaddrs * temp_address = NULL;
   int success = 0;
   success = getifaddrs(&ifaddress);
   if(success == 0) {
       temp_address = ifaddress;
       while(temp_address != NULL) {
           if(temp_address->ifa_addr->sa_family == AF_INET) {
             if([[NSString stringWithUTF8String:temp_address->ifa_name] isEqualToString:@"en0"]) {
        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_address->ifa_addr)->sin_addr)];
               }
           }
           temp_address = temp_address->ifa_next;
       }
   }

    NSLog(@"获取到的IP地址为:%@",ip);
    return ip;
}

获取外网IP地址

//获取外网 ip地址
+(NSString *)getIPaddress
{
    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];
        DLog(@"%@",dict);
        return dict[@"cip"] ? dict[@"cip"] : @"";

    }

    return @"";
}

备注:
也有网友推荐这两种,亲测不靠谱,有时会特别慢或获取不到IP

//获取外网 ip地址
+(NSString *)getIPaddress
{
    //方法一:【不靠谱】
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
    //方法二:【不靠谱方法二】
    /*
    http://ipof.in/json
    http://ipof.in/xml
    http://ipof.in/txt
    If you want HTTPS you can use the same URLs with https prefix. The advantage being that even if you are on a Wifi you will get the public address.
     */
   NSError *error;
   NSURL *ipURL = [NSURL URLWithString:@"http://ipof.in/txt"];
   NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];

    NSLog(@"获取到的IP地址为:%@",ip);
    
    return ip;
}

以上是关于IOS 获取IP地址的主要内容,如果未能解决你的问题,请参考以下文章

获取iOS设备ip地址

IOS 获取IP地址

如何在 iOS 设备上获取关联接入点的 IP 地址

苹果是不是允许 ios 应用程序通过 IP 地址获取用户位置

iOS--------获取当前连接的WiFi以及IP地址

如何在 Swift iOS 中获取路由器的 IP 地址