MacOS – On OS X is it possible to override DHCP assigned DNS servers but still keeping them for fallback

dnsmacosNetwork

By default I would like to use the google public DNS servers and to fallback to intranet ones when these are failing.

Is this possible? … I am looking for a setup that would not break when I move my laptop no other networks.

It would be acceptable if I found a solution specific to this wifi network connection (to do the trick only in this case, and to use defaults for others).

Best Answer

You can use ipconfig getpacket to find the DNS server that DHCP recommended:

$ ipconfig getpacket en0 
...
domain_name_server (ip_mult): {192.168.3.2, 192.168.42.1}
...

So, assuming you are using the Wi-Fi adapter and its device is en0, you can:

#!/bin/bash

default_servers=$( ipconfig getpacket en0 | \
   perl -ne'/domain_name_server.*: \{(.*)}/ && print join " ", split /,\s*/, $1' )
networksetup -setdnsservers Wi-Fi 127.0.0.1 $default_servers