IOS 获取IP地址

Somebody

获取内网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;
}
阅读 2.9k
1 声望
0 粉丝
0 条评论
1 声望
0 粉丝
文章目录
宣传栏