我的程序的一项任务是扫描本地wi-fi网络以查找同一网络中的任何设备/计算机。我找到了获得所有工作设备IP的解决方案,但没有设法得到它们的名称。我没有找到解决这个问题的任何线索。 有什么建议?
答案 0 :(得分:2)
要执行反向DNS查找,您需要调用CFHostGetNames
函数,如下所示:
+ (NSArray *)hostnamesForIPv4Address:(NSString *)address
{
struct addrinfo *result = NULL;
struct addrinfo hints;
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 succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!succeeded) {
return nil;
}
NSMutableArray *hostnames = [NSMutableArray array];
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames;
}
答案 1 :(得分:0)
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
现在我遇到总是在这一行失败了,我试图使用getnameinfo
函数,它仍然无法获取主机名