【问题标题】:how to resolve hostname from ip address in iOS Objective-C如何在 iOS Objective-C 中从 IP 地址解析主机名
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 事实上,gethostbyaddr 没有理由不能在 OS X / iOS 上运行。您的 DNS 服务器错误,或者您的代码错误,但理论上它应该可以工作。 host 192.168.0.101 说什么?
  • 根据我的经验,我已经在我的网络的 3 个活动设备上尝试过,但事实并非如此。我相信NSHost hostWithAddress: 仅适用于全球 IP,不适用于本地 IP。几个小时以来,我一直在尝试做 OP 想要做的事情。此外,gethostbyaddr 的结果是 NULL,所以 printf() OP 最后使用,最终会崩溃。你知道其他方法吗?
  • post OSX 平台而不是 IOS 减 1
猜你喜欢
  • 2012-08-04
  • 2011-01-10
  • 2014-02-26
  • 2010-11-05
  • 2013-03-25
  • 2019-09-29
  • 1970-01-01
  • 2011-03-12
  • 2014-10-13
相关资源
最近更新 更多