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 "" ""

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.

  • 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.

  • Now that’s elegant - no need to remove a setting if the interface can be disposable. Next steps is I will have to test if this is reliable when we script this remotely, but it’s probably no more dangerous than my “test” settings. – bmike Jul 6 '17 at 9:14
  • I came up with this little bash alias based on this answer: alias bouncewifi="sudo networksetup -createnetworkservice Wi-Fi2 $(networksetup -listallhardwareports|grep -A1 Wi-Fi|fgrep Device|awk '{print $2}') && sudo networksetup -removenetworkservice Wi-Fi && sudo networksetup -renamenetworkservice Wi-Fi2 Wi-Fi" Since my Wi-Fi is usually en0 and not en1, I used network setup to find out which device the current Wi-Fi was on and then executed the 3 above commands in order based on exit conditions of the previous command. This should be fairly safe to do remotely. – Matthew Du Puy Jul 1 '18 at 23:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .