关于ios:IOS-获取IP地址

5次阅读

共计 1875 个字符,预计需要花费 5 分钟才能阅读完成。

获取内网 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;
}
正文完
 0