问题
I have found this nice piece of code to get a hostname from a IP Address. The problem is that it always fail both on simulator and on my 3GS.
See below the code, the error is commented within:
+ (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;
}
Could someone say me what is wrong ?
回答1:
This sounds like a DNS lookup failure. The key part of the error message is:
{kCFGetAddrInfoFailureKey=8}
From the CFNetwork Error Codes Reference for kCFGetAddrInfoFailureKey
:
If an error of type
kCFHostErrorUnknown
is returned, this key returns the last error code returned bygetaddrinfo
in response to a DNS lookup. To interpret the results, look up the error code in/usr/include/netdb.h
.
From /usr/include/netdb.h
:
#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
Try using a different DNS server.
来源:https://stackoverflow.com/questions/19407309/cfhoststartinforesolution-always-fail-ubunteros