I know how to get the name behind an ip address using the terminal and dig. I.e:
dig @224.0.0.251 -p5353 -x 192.168.0.195 +short
However, I don't want to use NSTask in my application. How can I use NSHost to get the name behind an ip address within a LAN? I tried this, but it always returns nil:
NSHost *myHost = [NSHost hostWithAddress:@"192.168.0.195"];
NSLog(@"name: %@", [myHost name]);
Thanks a lot!
Edit: These methods/functions... +[NSHost hostWithAddress:] gethostbyaddr(3) - A BSD function ...seem to be the same as:
dig -x 192.168.0.195
If I use that dig command in the terminal it says that no servers could be reached. (Yes I don't have a DNS server in my LAN), so no wonder I get back nil.
It would be great if I could implement dig @224.0.0.251 -p5353 -x 192.168.0.195 +short
(bonjour multicast lookup) in my app without having to use NSTask. :)
It does not use
NSHost
, but uses the Bonjour-API and it seems to work as you want:The important part is using
DNSServiceQueryRecord
withkDNSServiceFlagsForceMulticast
. Look at https://developer.apple.com/library/mac/#documentation/Networking/Reference/DNSServiceDiscovery_CRef/dns_sd_h/index.html#//apple_ref/c/func/DNSServiceQueryRecord for more info about this function.You'll have to convert the IP address to in-addr.arpa.-format yourself, but that is not hard (the octets are backwards with "in-addr.arpa." at the end. IPv6 is probably similar, but I have not tested it).
It imports
resolv.h
(and you need to link it to libresolv), but only fordn_expand
. The data passed to the callback is compressed, anddn_expand
creates a human-readable representation.