Macos – How to use dnsmasq with DHCP-assigned DNS servers

dhcpdnsdnsmasqmacos

TL;DR version: How do I configure dnsmasq to fall back to the DNS servers pointed to by the DHCP server on my LAN, to enable switching wireless networks?

On my developer laptop I've recently started using dnsmasq so that I can capture all traffic to *.dev and redirect it to a virtual machine (using mod_vhost_alias).

For this to work I needed to configure my network settings so that dnsmasq (running at 127.0.0.1) is used as the primary DNS server, and the regular DNS servers are secondary – causing a fallback to those DNS servers when dnsmasq can not handle a domain lookup. This works well, except for the fact that the fallback DNS servers are now no longer configured through DHCP. Whenever I switch wireless networks, this breaks my connection – especially on networks that require authentication through a webpage (otherwise using a public DNS server like 8.8.8.8 would be an option).

I've tried reading the dnsmasq documentation, but none of the gazillion options seemed to do what I need, or perhaps I'm misunderstanding what some of the options do.

Note: this question was originally posted to ServerFault, considering the serverish-nature of dnsmasq. It was promptly closed due to Mac OS X not being a server OS. I don't have sufficient reputation on there to initiate a move, so against my better judgement I'm crossposting to SU.

Best Answer

Sounds like you're trying to achieve the exact same thing I've just setup on my new MacBook and have previously had working on my Linux dev machines.

As you know, manually adding 127.0.0.1 to your DNS entries in network settings is a pain because it has to be reapplied when changing network interfaces / connecting to alternate wifi access points and also prevents your machine from automatically picking up the DNS servers assigned through DHCP. Thankfully, the following solution completely avoids having to mess with your network settings so you can use DHCP as normal.

First off, if you've previously manually added 127.0.0.1 and external DNS servers to your network interface, now is the time to delete them and reset it back to DHCP defaults.

Having done that, you now need to create the folder /etc/resolver.

sudo mkdir /etc/resolver

Within this folder, you can now add text files named by domain to match and containing nameserver entries to use for those matching requests. OS X will automatically look in this folder for rules so it really is that simple.

So, for your setup (same as mine), we want to create a text file called /etc/resolver/dev (to catch all requests for *.dev) containing a standard nameserver entry for 127.0.0.1 (local IP used by dnsmasq).

sudo bash -c 'echo "nameserver 127.0.0.1" > /etc/resolver/dev'

Now all DNS requests for *.dev domains will be passed on to dnsmasq at 127.0.0.1 and anything not matching *.dev will be handled as normal by whatever DNS servers your DHCP has picked up.

Related Question