繁体   English   中英

如何从iOS Objective-C中的ip地址解析主机名

[英]how to resolve hostname from ip address in iOS Objective-C

我正在寻找一种方法来解决我的局域网中设备的主机名从其局域网上的IP地址。

我在C中编写了一个程序,它使用gethostbyaddr()函数在Linux上完美运行。

当我在OS X或iOS上尝试它时,它不起作用。

似乎OS X和iOS中的gethostbyaddr()存在问题。

无论如何,如果你有另一个想法从iOS的IP获取远程机器的主机名,它将成为我的一天。

这是我使用的代码:

第一次测试:

192.168.0.101是我们查询主机名的机器的IP地址。

#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

struct hostent *he;
struct in_addr ipv4addr;
inet_pton(AF_INET, "192.168.0.101", &ipv4addr);
he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s\n", he->h_name);

这段代码适用于linux,但它不适用于OS X或iOS。

第二次测试:

+ (NSArray *)hostnamesForAddress:(NSString *)address {
    // Get the host reference for the given address.
    struct addrinfo      hints;
    struct addrinfo      *result = NULL;
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags    = AI_NUMERICHOST;
    hints.ai_family   = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;
    int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &hints, &result);
    if (errorStatus != 0) return nil;
    CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
    if (addressRef == nil) return nil;
    freeaddrinfo(result);
    CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
    if (hostRef == nil) return nil;
    CFRelease(addressRef);
    BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
    if (!isSuccess) return nil;

    // Get the hostnames for the host reference.
    CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
    NSMutableArray *hostnames = [NSMutableArray array];
    for (int currentIndex = 0; currentIndex < [(NSArray *)hostnamesRef count]; currentIndex++) {
        [hostnames addObject:[(NSArray *)hostnamesRef objectAtIndex:currentIndex]];
    }

    return hostnames;
}

这段代码停留在CFHostStartInfoResolution,此时返回nil。

Thx提前。

它实际上是一个单行。 [[NSHost hostWithAddress:@"173.194.34.24"] name]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM