After using `networksetup -setdnsservers Wi-Fi "8.8.8.8" "8.8.4.4"` how do I clear them?

I'm looking to script a temporary DNS server change to override the DHCP response I get from the network. I've figured out I can use networksetup but once we're done testing. Before I push to production, I figure I should know how to undo this.

How can I script to clear these changes and restore the settings the network provides now as if I never ran the following script?

networksetup -setdnsservers Wi-Fi "8.8.8.8" "8.8.4.4"

It's not feasible to save any the previous settings and I'm looking to remove the setting so that the actual new values can be retrieved from the network as opposed to saving what the settings were previously so I don't save an old value that is no longer correct.

Basically, I'm looking to ipconfig /renew on macOS.


Solution 1:

If you're concerned only about cleaning DNS entries, the command help gives you instructions what to do:

Usage: networksetup -setdnsservers <networkservice> <dns1> [dns2] [...]
       Set the <networkservice> DNS servers to <dns1> [dns2] [...]. Any 
       number of dns servers can be specified. Specify "Empty" for <dns1> 
       to clear all DNS entries.

In my case

sudo networksetup -setdnsservers Wi-Fi "Empty"

Solution 2:

  • Create a new network service with the respective interface (e.g. en1 = AirPort):

    sudo networksetup -createnetworkservice Wi-Fi2 en1

  • Remove the one with the custom DNS settings:

    sudo networksetup -removenetworkservice Wi-Fi

  • Rename the new network service to the original name:

    sudo networksetup -renamenetworkservice Wi-Fi2 Wi-Fi

In my environment the new service fetched DHCP and its new settings automatically. You may have to set it with sudo networksetup -setdhcp Wi-Fi explicitly or look at the DHCP response for the interface and parse the supplied DNS ip(s) with ipconfig getpacket en1 though.