Multicast DNS (mDNS) Implementation

7.2.5 · active · verified Sun Apr 19

multicast-dns is a low-level, pure JavaScript implementation of the Multicast DNS (mDNS) protocol, widely used for zero-configuration service discovery, commonly known as Apple's Bonjour or Avahi. It facilitates device and service discovery on a local network by sending DNS queries over UDP multicast to the standard address `224.0.0.251:5353` and listening for corresponding responses. The current stable version, 7.2.5, provides an event-driven API for both querying for and responding to mDNS packets. It supports various DNS record types including A, AAAA, PTR, SRV, TXT, and HINFO, allowing applications to discover network services and resolve local hostnames. The library offers fine-grained control over network interfaces, ports, and other UDP socket options, making it a foundational component for peer-to-peer and local area network applications that require automatic service registration and discovery without relying on a central DNS server. It maintains a focus on low-level network interactions rather than abstracting into a high-level service browser.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a `multicast-dns` instance, logs incoming query and response packets, demonstrates how to query for specific records, and how to respond to queries for a known service, then destroys the instance.

import createMdns from 'multicast-dns';

const mdns = createMdns();

mdns.on('response', function(response) {
  console.log('Got a mDNS response packet:', JSON.stringify(response, null, 2));
});

mdns.on('query', function(query) {
  console.log('Got a mDNS query packet:', JSON.stringify(query, null, 2));
  // Example: Respond to a query for 'my-service.local'
  if (query.questions[0] && query.questions[0].name === 'my-service.local') {
    mdns.respond({
      answers: [{
        name: 'my-service.local',
        type: 'A',
        ttl: 120,
        data: '127.0.0.1' // Replace with actual IP
      }]
    });
    console.log('Responded to query for my-service.local');
  }
});

// Query for an A record for a local hostname (e.g., your-hostname.local)
mdns.query({
  questions:[
    {
      name: 'your-hostname.local',
      type: 'A'
    },
    {
      name: 'my-service.local',
      type: 'SRV'
    }
  ]
});

console.log('Sent mDNS query for your-hostname.local and my-service.local');

// Destroy the instance after a timeout to prevent resource leaks in short-lived scripts
setTimeout(() => {
  mdns.destroy();
  console.log('mDNS instance destroyed.');
}, 10000);

view raw JSON →