uses following method to get host-name from ip address.
OK, so, then reverse DNS it is.
Before we start I want to be clear that using networking APIs, like
CFHost, synchronously is not recommended. It’s much better to use the async variant. For an example of this with
CFHost, see
CFHostSample.
Also, using synchronous networking APIs on an app’s main thread is a
really bad idea. On macOS it can result in
SPODing and on iOS-based platforms you can end up being killed by the watchdog. See QA1693
Synchronous Networking On The Main Thread for my take on this.
Still, the above is orthogonal to your main issue. IIRC
CFHost will always use unicast DNS for reverse name lookups, and thus won’t work for local IP addresses. You’re not the first person to ask about this on DevForums but, alas, my response is no longer available (it was on the first, non-public iteration on DevForums; see
this for details).
Normally in such cases I’d repost the answer here but, honestly, the code in that answer is
really old. So, rather than do that I’m going to do a quick recap.
The key idea here is to use the low-level DNS-SD API (
<dns_sd.h>) for your reverse name lookup. This API supports a flag,
kDNSServiceFlagsForceMulticast, that lets you force the request to go over multicast DNS rather than unicast DNS. So, to reverse lookup 192.168.1.39 you’d use something like this:
Code Block | err = DNSServiceQueryRecord( |
| &self->sdRef, |
| kDNSServiceFlagsForceMulticast, |
| 0, |
| "39.1.168.192.in-addr.arpa.", |
| kDNSServiceType_PTR, |
| kDNSServiceClass_IN, |
| DNSCallback, |
| (__bridge void *)(self) |
| ); |
The DNS-SD API is low-level and thus quite tricky to use. A good starting point is the
DNSSDObjects sample code, which shows how to do the basics with that API. You can then modify it to run your specific query.
Oh, and before you write any code you should confirm that the devices in question actually export
PTR records over multicast DNS. You can do that using the
dns_sd tool:
Code Block | % ping fluffy.local. |
| PING fluffy.local (192.168.1.39): 56 data bytes |
| 64 bytes from 192.168.1.39: icmp_seq=0 ttl=64 time=116.423 ms |
| ^C |
| … |
| % dns-sd -Q 39.1.168.192.in-addr.arpa. PTR |
| DATE: ---Fri 07 May 2021--- |
| 10:23:50.636 ...STARTING... |
| Timestamp A/R Flags if Name Type Class Rdata |
| 10:23:50.639 Add 2 0 39.1.168.192.in-addr.arpa. PTR IN Fluffy.local. |
| ^C |
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"