1

我发现了一段很好的代码来从 IP 地址获取主机名。问题是它在模拟器和我的 3GS 上总是失败。

见下面的代码,错误注释在:

+ (NSArray *)hostnamesForAddress:(NSString *)address {
    // Get the host reference for the given address.
    CFStreamError streamError;
    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, &streamError);
    // always false
    if (!isSuccess){
        NSLog(@"error:%@",[self convertCFStreamErrorIntoNSError:streamError]);
        // error:Error Domain=kCFErrorDomainCFNetwork Code=2 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.)" UserInfo=0x1cd29190 {kCFGetAddrInfoFailureKey=8}
        return nil;
    }

    // Get the hostnames for the host reference.
    CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
    NSMutableArray *hostnames = [NSMutableArray array];
    for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
        [hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
    }

    return hostnames;
}

有人可以告诉我有什么问题吗?

4

1 回答 1

0

这听起来像是 DNS 查找失败。错误消息的关键部分是:

{kCFGetAddrInfoFailureKey=8}

来自CFNetwork 错误代码kCFGetAddrInfoFailureKey参考:

如果返回类型错误,kCFHostErrorUnknown则此键返回最后一个返回的错误代码getaddrinfo以响应 DNS 查找。要解释结果,请在 中查找错误代码/usr/include/netdb.h

来自/usr/include/netdb.h

#define EAI_NONAME  8  /* hostname nor servname provided, or not known */

尝试使用不同的 DNS 服务器。

于 2013-10-16T16:19:41.940 回答