开发者社区 问答 正文

gethostbyname( )在ios6中不工作

我用gethostbyname( )获取设备的ip,在ios5中运行正常,但是在ios6中,返回的host值是空,下面就是我的代码:

// retun the host name
- (NSString *)hostname
{
    char baseHostName[256];
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '\0';

#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
    return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}

// return IP Address
- (NSString *)localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {
        herror("resolv");
        return nil;
    }
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}

在ios5和ios6的模拟器中都正常,但是到ios6针剂就不行了,不知道是怎么回事?有没有其他方法在ios6获取设备ip的?

展开
收起
爵霸 2016-03-26 10:00:37 2430 分享 版权
1 条回答
写回答
取消 提交回答
  • 改用 getifaddrs + getnameinfo 可以枚举出所有接口的ip。gethostbynameipv6是无效的。

    2019-07-17 19:15:27
    赞同 展开评论
问答地址: