Flush cache of DNS on macOS Sierra & High Sierra

sudo dscacheutil -flushcache does nothing useful related to DNS cache entries - at least in non-LDAP environments and 10.9-10.13.

sudo killall -HUP mDNSResponder sends a hang up to mDNSResponder, launchd will restart the daemon and the DNS cache will be cleared as spillover effect.

This can easily be tested with the following command sequence:

sudo killall -INFO mDNSResponder

default 03:54:55.672826 +0200 mDNSResponder Cache size 282 entities; 189 in use (73 group, 29 multicast, 87 unicast); 2 referenced by active questions
default 03:54:55.694219 +0200 mDNSResponder Unicast Cache size 1769

sudo dscacheutil -flushcache
sudo killall -INFO mDNSResponder

default 03:55:52.148629 +0200 mDNSResponder Cache size 282 entities; 180 in use (79 group, 19 multicast, 82 unicast); 2 referenced by active questions
default 03:55:52.157180 +0200 mDNSResponder Unicast Cache size 1992

sudo killall -HUP mDNSResponder
sudo killall -INFO mDNSResponder

default 03:56:39.446829 +0200 mDNSResponder Cache size 282 entities; 8 in use (4 group, 0 multicast, 4 unicast); 2 referenced by active questions
default 03:56:39.466259 +0200 mDNSResponder Unicast Cache size 121

To get the results above open Console.app, choose your hostname in "Devices" and use a filter mDNSResponder & Cache size:

enter image description here

I've discovered an alternate way to clear the DNS cache, and you don't need any root permissions. Here's the shell script I use to help automate this.

DNSSERVERS=`networksetup -getdnsservers $NETWORKSVC | tr '\n' ' '`

if [ "$DNSSERVERS" = "There aren't any DNS Servers set on Wi-Fi. " ]; then

networksetup -setdnsservers $NETWORKSVC
networksetup -setdnsservers $NETWORKSVC $DNSSERVERS

Set your network service name in the first line. The second line gets your currently set DNS Servers. As the getdnsservers subcommand returns one DNS server per line, we use tr (transform) to change the newlines into spaces.

The if statement handles the special case of where your DNS servers have been handed down via DHCP.

Next, we change the DNS server to an obviously fake one. This triggers the DNS cache to be cleared. You can confirm that it is actually cleared using klanomath's technique.

The last line restores your original DNS servers. The setdnsservers subcommand expects the list of DNS servers to be space separated.

You can also just do all of this in System Preferences, but the shell script is faster and is basically instant.