Discovering Local Network Services with Bonjour

Ever wonder how your computer or phone automatically finds audio devices, display mirroring devices, and Alexa and HomeKit accessories on your local network? This works even on home networks with no central network infrastructure. This is possible through a pair of technologies called mdns and DNS-SD, sometimes collectively known as Bonjour.

mdns (Multicast DNS)

This is exactly what it sounds like: the regular-old DNS protocol, except that instead of relying on a client-server architecture, it uses peer-to-peer with multicast UDP. Using the mdns protocol, one machine can multicast a DNS query to the other machines on the local network, and they can all reply. In addition to the one-shot request-response query that’s typical for DNS, mdns defines mechanisms to continue “browsing” by retransmitting a query over time, in case new response appears (which may happen when a new device joins the network). Devices advertise their presence when joining a network, and periodically thereafter. This enables fast discovery if a device joins while some device is browsing for it.

Using just the DNS protocol in this new way gives us the ability to resolve from a local domain name like “Zacharys-MacBook.local.” to an IP address. Responses include regular A records for IPv4 and AAAA for IPv6. Keep in mind that a single domain name may map to multiple addresses across both IPv4 and IPv6, and queries and responses may use multiple network connections (e.g., Ethernet and Wi-Fi).

DNS-SD (DNS Service Discovery)

While using the DNS protocol in this new way allows us to resolve local domain names, it isn’t sufficient to find services of a particular type. For example, rather than resolving “Zacharys-MacBook.local.”, I want to discover printers or Amazon Alexa devices or Apple HomeKit devices.

To search by service type instead of by domain name, we need DNS-SD. This introduces a couple of new record types: SRV and TXT records. SRV records contain the domain name and port a service is running on, and TXT records have other useful metadata about a service. Multiple records can be returned in a single response, so requiring SRV, TXT, A/AAAA records doesn’t require many separate mdns responses.

Used in combination, mdns and dns-sd provide a complete way to discover services on the network. Next time you need to implement a discoverable network service or don’t know your machine’s IP address, check out these options.

Digging Deeper

If you want to learn, check out the RFCs: RFC 6762 for mdns and RFC 6763 for DNS-SD

Standard