I'm looking for a way to resolve the hostname of a device in my LAN from its ip address on this LAN.
I wrote a program in C which works perfectly on Linux using gethostbyaddr() function.
When I tried that on OS X or iOS it doesn't work.
It seems that there is a problem with gethostbyaddr() in OS X and iOS.
Anyway, if you have another idea to get hostname of remote machine from it's IP in iOS, it'll make my day.
This is the code I used:
First test:
192.168.0.101 is the ip address of the machine that we are querying for hostname.
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
struct hostent *he;
struct in_addr ipv4addr;
inet_pton(AF_INET, "192.168.0.101", &ipv4addr);
he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s\n", he->h_name);
This code works well on linux, but it doesn't on OS X nor iOS.
Second test:
+ (NSArray *)hostnamesForAddress:(NSString *)address {
// Get the host reference for the given address.
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, NULL);
if (!isSuccess) return nil;
// Get the hostnames for the host reference.
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
NSMutableArray *hostnames = [NSMutableArray array];
for (int currentIndex = 0; currentIndex < [(NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames;
}
This code stucks at CFHostStartInfoResolution returning nil at this point.
Thx in advance.
It's actually a one-liner.
[[NSHost hostWithAddress:@"173.194.34.24"] name]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With