我正在寻找一种方法,可以根据局域网内某个设备的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。
先行致谢。