如何在iOS Objective-C中通过IP地址解析主机名

11

我正在寻找一种方法,可以根据局域网内某个设备的IP地址解析出该设备的主机名。

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

但是当我在OS X或iOS上尝试时,它就无法工作。

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

如果您有另外的想法来获取iOS系统下远程机器的主机名,那将使我的一天变得美好。

这是我使用的代码:

第一次测试:

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。

先行致谢。


我认为你想要使用CFHost API,请查看这个链接 - Jonathan
我尝试使用CFHost API,但是当我尝试从网络上的现有IP地址检索主机名时,出现了相同的问题,请求超时。 但是当我尝试解析127.0.0.1(即本地主机地址)时,它可以正常工作。 - taredhot
你解决了这个问题吗?我也遇到了相同的 nil 值 @taredhot - Alejandro Vargas
你找到解决方案了吗? - BlackM
1个回答

2

其实这只是一行代码。 [[NSHost hostWithAddress:@"173.194.34.24"] name]


1
实际上,在OS X / iOS上没有理由gethostbyaddr不起作用。要么是您的DNS服务器有问题,要么是您的代码有问题,但从理论上讲它应该可以工作。host 192.168.0.101输出什么? - Ecco
根据我的经验,我已经在我的网络中尝试了3个活动设备,这是不行的。我相信NSHost hostWithAddress:只适用于全局IP,而不是本地IP。我已经尝试了几个小时来实现OP想要的功能。此外,gethostbyaddr的结果为NULL,因此OP在结尾处使用的printf()最终会导致崩溃。你知道其他方法吗? - isklikas
针对OSX平台而非IOS,将其减少1。 - famfamfam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接