CFHostStartInfoResolution总是失败ubunteros

时间:2013-10-16 15:19:43

标签: iphone ios ip-address lookup cfnetwork

我找到了这段很好的代码来从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;
}

有人能说我出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

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

{kCFGetAddrInfoFailureKey=8}

来自kCFGetAddrInfoFailureKey的{​​{3}}:

  

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

来自/usr/include/netdb.h

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

尝试使用其他DNS服务器。