11

我正在寻找一种方法来从该 LAN 上的 IP 地址解析我 LAN 中设备的主机名。

我用 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。

提前谢谢。

4

1 回答 1

2

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

于 2012-12-08T22:57:47.150 回答