【问题标题】:gethostbyname( ) failed in iOS6在 iOS6 中 gethostbyname() 失败
【发布时间】:2012-12-29 15:13:10
【问题描述】:

我使用 gethostbyname() 来获取设备 IP。在 iOS5 中,它运行良好。但是在 iOS6 中,gethostbyname() 返回的主机值是 NULL。下面是我获取设备当前本地 IP 的代码。

// 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 设备失败。 gethostbyname() 有什么区别? 或者你有什么其他解决方案可以在 iOS6 中获取本地 ip?

【问题讨论】:

    标签: iphone ios6


    【解决方案1】:

    有几个可能的问题:

    • 也许您有一个 IPv6 地址(gethostbyname() 仅适用于 IPv4),
    • 或从主机名到 IP 地址的名称解析无法正常工作。

    以下代码将所有本地地址作为字符串数组返回。它不依赖于名称解析,适用于 IPv4 和 IPv6 地址。

    #include <sys/types.h>
    #include <sys/socket.h>
    #include <ifaddrs.h>
    #include <net/if.h>
    #include <netdb.h>
    
    // return all local IP addresses
    - (NSArray *)localIPAddresses
    {
        NSMutableArray *ipAddresses = [NSMutableArray array] ;
    
        struct ifaddrs *allInterfaces;
    
        // Get list of all interfaces on the local machine:
        if (getifaddrs(&allInterfaces) == 0) {
            struct ifaddrs *interface;
    
            // For each interface ...
            for (interface = allInterfaces; interface != NULL; interface = interface->ifa_next) {
                unsigned int flags = interface->ifa_flags;
                struct sockaddr *addr = interface->ifa_addr;
    
                // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
                if ((flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)) {
                    if (addr->sa_family == AF_INET || addr->sa_family == AF_INET6) {
    
                        // Convert interface address to a human readable string:
                        char host[NI_MAXHOST];
                        getnameinfo(addr, addr->sa_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    
                        [ipAddresses addObject:[[NSString alloc] initWithUTF8String:host]];
                    }
                }
            }
    
            freeifaddrs(allInterfaces);
        }
        return ipAddresses;
    }
    

    【讨论】:

    • 在wifi下,这个方法返回3G地址和wifi地址。如何找出当前使用的是哪一个?
    猜你喜欢
    • 2014-05-31
    • 2017-01-16
    • 2013-08-22
    • 2017-09-18
    • 2019-07-20
    • 1970-01-01
    • 2011-07-13
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多