如何从ios中的IP地址获取dns名称

时间:2014-05-02 06:07:19

标签: ios objective-c

我使用以下代码,CFHostStartInfoResolution方法始终returns false

Boolean result;

 CFHostRef hostRef;

CFArrayRef addresses;

 NSString  *strHostName=@"192.149.252.125";
    BOOL bResolved;

    CFDataRef myDataRef = (__bridge CFDataRef)[strHostName dataUsingEncoding:NSASCIIStringEncoding];
    hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, myDataRef);
    if (hostRef) {
        CFStreamError *e = NULL;
        result = CFHostStartInfoResolution(hostRef, kCFHostNames, e);
        if (result == TRUE) {
            // Get the array of IP the hostname resolved to
            addresses = CFHostGetNames(hostRef, &result);
        }
    }

    bResolved = result == TRUE ? true : false;
    if(bResolved)
    {
        struct sockaddr_in*     remoteAddr;
        for(int i = 0; i < CFArrayGetCount(addresses); i++)
        {
            CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addresses, i);
            remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData);
            if(remoteAddr != NULL)
            {
                NSString *strDNS =[NSString stringWithCString:inet_ntoa(remoteAddr->sin_addr) encoding:NSASCIIStringEncoding];
                NSLog(@"RESOLVED %d:<%@>", i, strDNS);
            }
        }
    }

}

0 个答案:

没有答案