When you don’t have a monitor and have plugged your Raspberry Pi in to a network – how do you know which IP address it got? This was a real problem for me with a plug-and-play use for the RaspberryPi that I’m working on. Without knowing anything about the network I’m on, how can I find my Raspberry Pi amongst all the other devices. Some suggested just searching the subnet, which is fine if its a /24, but not so helpful for a /8. I wanted a way that was fast and would work no matter the network size. It was during research that I came across mDNS and its various implementations.
There appear to be two implementations of mDNS, one is the Microsoft way the other the Apple way (Bonjour in their words). These work in similar ways, however it seems Microsoft is on their own and the Linux world has only embraced the Apple method. The first step is to get your computer to be able to resolve mDNS queries, if you’re an Apple user it will support this out of the box as Bonjour is included. If you’re a Windows user then you’ll need to install the Bonjour service. If you’ve installed iTunes or some of Apple’s other products there is a good chance Bonjour is already installed (check your Windows Services for Bonjour). If not then you can download it from https://support.apple.com/kb/DL999
Next you need to install mDNS on to the Raspberry Pi. You can do this via the command “sudo apt-get install libnss-mdns avahi-utils”. The moment this is run you should be able to resolve the name you assigned your Raspberry Pi from your PC. You may need to suffix it with “.local”, for example “mypi.local”.
One added benefit is the ability to publish several computers with a common service name. Using the Avahi application you can specify the name, port and description of a service, which can then be discovered on the network. This allows you to dynamically look up available computers and act accordingly. The command to start the publishing is:
avahi-publish -s “service name” _service._tcp 443 “name”
A search for the name specified, in this case “_service._tcp” will result in details of the service being retrieved and the names of all computers actively publishing. Great if you have a number of Raspberry Pis running but you don’t know which will be on at any one time.
Of course if you’re writing a Windows application and you don’t want to depend upon the Bonjour service being installed there are other options. For example there is a .Net Framework implementation of Bonjour that permits name resolution directly within the code available here https://github.com/automaters/bonjour.net