Skip to content

Instantly share code, notes, and snippets.

@Gomah
Created June 16, 2026 10:32
Show Gist options
  • Select an option

  • Save Gomah/7f9264cf24fa8d73bb5d4137ccaa3e3d to your computer and use it in GitHub Desktop.

Select an option

Save Gomah/7f9264cf24fa8d73bb5d4137ccaa3e3d to your computer and use it in GitHub Desktop.
Reset DNS servers to Cloudflare's malware-blocking resolvers
#!/usr/bin/env bash
#
# restore-dns.sh — Reset DNS servers to Cloudflare's malware-blocking resolvers.
#
# Why this exists: a VPN client rewrites your DNS settings while connected and
# often fails to restore them on disconnect, leaving you with no (or the wrong)
# resolvers. macOS stores DNS per network *service* (Wi-Fi, Ethernet, ...) in
# the system configuration database, so we set it there with `networksetup`
# rather than editing /etc/resolv.conf (which macOS regenerates and ignores).
#
# Usage:
# ./restore-dns.sh # apply to all active network services
# ./restore-dns.sh Wi-Fi # apply only to the named service(s)
set -euo pipefail
# Cloudflare for Families — block malware (1.1.1.2 / 1.0.0.2 + IPv6).
DNS_SERVERS=(
1.1.1.2
1.0.0.2
2606:4700:4700::1112
2606:4700:4700::1002
)
# networksetup -setdnsservers needs root to write the system config.
if [[ $EUID -ne 0 ]]; then
exec sudo "$0" "$@"
fi
# Determine which network services to touch.
if [[ $# -gt 0 ]]; then
services=("$@")
else
# Find services that currently have an IPv4 address = the ones actually in use.
# `listallnetworkservices` prefixes disabled services with '*'; we skip those.
services=()
while IFS= read -r svc; do
[[ $svc == \** ]] && continue # skip disabled services
[[ $svc == "An asterisk"* ]] && continue # skip the header line
if networksetup -getinfo "$svc" 2>/dev/null | grep -q "^IP address: [0-9]"; then
services+=("$svc")
fi
done < <(networksetup -listallnetworkservices)
fi
if [[ ${#services[@]} -eq 0 ]]; then
echo "No active network services found." >&2
exit 1
fi
for svc in "${services[@]}"; do
echo "Setting DNS on \"$svc\" -> ${DNS_SERVERS[*]}"
networksetup -setdnsservers "$svc" "${DNS_SERVERS[@]}"
done
# Flush the resolver cache so the new servers take effect immediately.
dscacheutil -flushcache 2>/dev/null || true
killall -HUP mDNSResponder 2>/dev/null || true
echo "Done. Verify with: scutil --dns | grep nameserver"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment