Get host name From IP address iOS 10

爱⌒轻易说出口 提交于 2020-01-03 19:34:30

问题


I need to fetch host name from ip address. Am able to fetch ip, mac addresses of all devices connected to my devices network, but hostname always returns nil.

i had tried below code snippets to retrieve hostname but it always returns nil in my network

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);
  }

来源:https://stackoverflow.com/questions/43463996/get-host-name-from-ip-address-ios-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!