swiftcore-foundationdns-sd

How to do a CNAME record lookup in swift


I found some example code online that I'm trying to use to do a CNAME record lookup (notice that I pass a callback block that I want to be run):

DNSServiceQueryRecord(serviceRef, 0, 0, domainName, UInt16(kDNSServiceType_CNAME), UInt16(kDNSServiceClass_IN), callback, &mutableCompletionHandler);
DNSServiceProcessResult(serviceRef.pointee)

The problem is that this code is getting blocked at DNSServiceProcessResult(serviceRef.pointee) and the callback is never called. According to Apple's documentation for DNSServiceProcessResult, I need to

Use DNSServiceRefSockFD in conjunction with a run loop or select() to determine the presence of a response from the server before calling this function to process the reply without blocking.

So I looked at DNSServiceRefSockFD and found that I could create a dnssd_sock_t with DNSServiceRefSockFD(serviceRef.pointee). But now that I have the socket, I'm not sure how to "use it in conjunction with a run loop" as an event source for the run loop (according to the DNSServiceRefSockFD documentation).

I'm just not understanding how this works. I don't understand how to use the dnsssd_sock_t as an event source to a run loop so that I can call DNSServiceProcessResult at the right time without blocking so that my callback will actually run.

If it's better to use the socket as a kqueue event source or in a select() loop (as the documentation mentions), I'm fine with that, but I don't know how to do that either.

CoreFoundation can be quite cryptic, so any help is much appreciated!

And if there's a better way to do a CNAME record lookup then, by all means, please share!


Solution

  • See my (ethan-gerardot) comments on https://gist.github.com/fikeminkel/a9c4bc4d0348527e8df3690e242038d3

    The first paragraph answers how to get the callback to be called without blocking.