Publishing Services over mDNS in C

For some time now I’ve been looking into mDNS-advertised services. My aim was to advertise a service using mDNS in a C program.

Typically, doing this is really easy: call the Bonjour or Avahi APIs, and the system-wide daemon will do the rest for you. The problem arises when there is no system-wide daemon such as mDNSResponder (if you’re on a Mac or Windows) or Avahi (for the other OSes). This usually happens when you’re on an embedded system, like a router that runs Linux.

One way to solve this would be to cross-compile Avahi or Apple’s mDNSResponder for your platform. I chose another alternative - embedding a simple mDNS responder into the C program. Of course this implementation needs to be as lightweight as possible, meaning little or no external dependencies.

I thought it would be trivial to read the specifications and implement the mDNS protocol, but it turned out to be quite a bit of work. A few days into writing my own implementation, I found mdnsd written by Daniel Pelleg. I almost killed myself.

So here, I present my implementation that works - tinysvcmdns. To publish a service, you need only make 4 calls:

  1. mdnsd_start() to start the main thread
  2. mdnsd_set_hostname() to set the hostname and IP address
  3. mdnsd_register_svc() to register a service and begin an announcement
  4. mdnsd_stop() when you no longer need to respond to mDNS queries

It may be buggy, and it doesn’t do name collision detections, but it works. I hope to improve upon it as I use it in my project(s). tinysvcmdns is open-source, under the GNU LGPL “modified” BSD license (Update 2012-03-26: changed the software license).

mdnsd pretty much has a similar offering, but it implements features like name collision detection.

If you have the need to publish services over mDNS very simply, I hope you can benefit from this post, and will not re-invent the wheel like I did.