获取主机名来自IP地址iOS 10

时间:2017-04-18 05:08:38

标签: objective-c networking ios10 ip-address ipconfig

我需要 从IP地址获取主机名 。能够获取连接到我的设备网络的所有设备的ip,mac地址,但 主机名始终返回nil

我曾尝试过以下代码段来检索主机名,但它总是在我的网络中返回nil

CODE SNIPPET 1

+(NSString *)getHostFromIPAddress:(NSString*)ipAddress {
struct addrinfo *result = NULL;
struct addrinfo hints;

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([ipAddress 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 succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!succeeded) {
    return nil;
}

NSMutableArray *hostnames = [NSMutableArray array];

CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
    [hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}

return hostnames[0];
} 

CODE SNIPPET 2

#pragma mark - Get Host from IP
+(NSString *)getHostFromIPAddress:(NSString*)ipAddress {
struct addrinfo *result = NULL;
struct addrinfo hints;

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 error;
struct addrinfo *results = NULL;

error = getaddrinfo([ipAddress cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL, &results);
if (error != 0)
{
    NSLog (@"Could not get any info for the address");
    return @""; // or exit(1);
}

for (struct addrinfo *r = results; r; r = r->ai_next)
{
    char hostname[NI_MAXHOST] = {0};
    error = getnameinfo(r->ai_addr, r->ai_addrlen, hostname, sizeof hostname, NULL, 0 , 0);
    if (error != 0)
    {
        continue; // try next one
    }
    else
    {
        return [NSString stringWithUTF8String:hostname];;
        NSLog (@"Found hostname: %s", hostname);
        break;
    }
}

freeaddrinfo(results);
  }

0 个答案:

没有答案