Skip to content

Instantly share code, notes, and snippets.

@SandraMct
Last active November 19, 2024 13:33
Show Gist options
  • Save SandraMct/abb7750f8afe25bf8ea9eab014b0ad1e to your computer and use it in GitHub Desktop.
Save SandraMct/abb7750f8afe25bf8ea9eab014b0ad1e to your computer and use it in GitHub Desktop.
WSL auto-generate DNS resolution
#!/bin/bash
# Remove the file for resolver configuration
chattr -i /etc/resolv.conf
rm -Rf /etc/resolv.conf
# Use the default routing table entry as DNS for WSL
echo "nameserver $(ip route | grep default | grep -Poe "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+")" > /etc/resolv.conf

Fix DNS on WSL once and for all

Tested on Ubuntu-20.04, Windows 11

Create a script that will be executed at WSL boot and that will use the default routing table as DNS (which is the host's ip).

Auto-DNS resolver

The solution consists in using the host (Windows) as DNS. It will then use its own configuration.

  1. First gain root privileges: sudo bash
  2. Go to root home to work: cd ~
  3. Create the file reset-dns.sh with the content of reset-dns.sh
  4. Make this file executable: chmod +x reset-dns.sh
  5. Either create a symlink or move this script to /usr/local/bin (or in any other folder that is in root's $PATH)
  6. From now on you can try the script to make sure this works:
  reset-dns.sh
  ping www.github.com

Apply to WSL boot

See Boot settings

  1. Still with root access, change WSL configuration in /etc/wsl.conf:
  • Under [network], add generateResolvConf=false to make sure WSL will not try to generate it itself
  • Under [boot], add command=reset-dns.sh to launch the script you created earlier when booting You can see my wsL.conf to compare.
  1. Stop WSL using another terminal (like cmd): wsl --terminate Ubuntu-20.04 or more brutal wsl --shutdown
  2. Now when you launch a new Ubuntu terminal, you will be able to join the whole World Wide Web 😁 You can try to change network to make sure the solution fits your case.
  3. Usually, you should not need to use the script again, but you can use sudo reset-dns.sh to reset the DNS again at any time.
[network]
generateResolvConf=false
[boot]
systemd=true
command=reset-dns.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment