【发布时间】:2012-11-30 16:18:10
【问题描述】:
我正在寻找一种方法来从该 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。
提前致谢。
【问题讨论】:
-
我认为你想要 CFHost API,查看this
-
我尝试使用 CFHost API,当我尝试从网络上的现有 IP 地址检索主机名时出现同样的问题,请求超时。但是当我尝试解析本地地址的 127.0.0.1 时,它可以工作。
-
您解决了这个问题吗?我得到相同的零值@taredhot
-
您找到解决方案了吗?
标签: objective-c ios hostname