gethostbyname( ) failed in iOS6

后端 未结 1 2028
灰色年华
灰色年华 2021-01-15 03:02

I use gethostbyname() to get the device IP. In iOS5, it works well. But in iOS6, the host value returned by gethostbyname() is NULL. Below is my code to get the current loca

相关标签:
1条回答
  • 2021-01-15 03:35

    There are several possible problems:

    • Perhaps you have an IPv6 address (gethostbyname() works only with IPv4),
    • or the name resolution from the hostname to IP address does not work correctly.

    The following code returns all local addresses as an array of strings. It does not depend on name resolution and works with both IPv4 and IPv6 addresses.

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题