美文网首页
IOS获取设备的ip地址

IOS获取设备的ip地址

作者: FrankHuang93 | 来源:发表于2017-10-27 16:06 被阅读46次

    一、获取公网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 : @"");
    }

    这个ipDic里面的数据结构如下图,可以获取IP的所在地和国家id等等的信息

    image.png

    二、获取内网的私有IP地址

    -(NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL) {
    if(temp_addr->ifa_addr->sa_family == AF_INET) {
    // Check if interface is en0 which is the wifi connection on the iPhone
    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
    // Get NSString from C String
    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
    }
    }
    temp_addr = temp_addr->ifa_next;
    }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
    }

    相关文章

      网友评论

          本文标题:IOS获取设备的ip地址

          本文链接:https://www.haomeiwen.com/subject/npfdpxtx.html