Skip to content

Instantly share code, notes, and snippets.

@toryano0820
Last active July 2, 2024 11:01
Show Gist options
  • Save toryano0820/6ee3bff2474cdf13e70d972da710996a to your computer and use it in GitHub Desktop.
Save toryano0820/6ee3bff2474cdf13e70d972da710996a to your computer and use it in GitHub Desktop.
For WSL2: Fixes "Connection Refused" issue when accessing Windows localhost services. Run with "sudo sh wsl2-ubuntu-map-win-localhost.sh" !!! Remember to backup "/etc/hosts" just in case !!!
nameserver=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}') # find nameserver
[ -n "$nameserver" ] || "unable to find nameserver" || exit 1 # exit immediately if nameserver was not found
echo "##### nameserver found: '$nameserver'"
localhost_entry=$(grep -v "127.0.0.1" /etc/hosts | grep "\slocalhost$") # find localhost entry excluding 127.0.0.1
if [ -n "$localhost_entry" ]; then # if localhost entry was found
echo "##### localhost entry found: '$localhost_entry'"
sed -i "s/$localhost_entry/$nameserver localhost/g" /etc/hosts # then update localhost entry with the new $nameserver
else # else if entry was not found
echo "##### localhost entry not found"
echo "$nameserver localhost" >> /etc/hosts # then append $nameserver mapping to localhost
fi
cat /etc/hosts # display to confirm
@20171003234
Copy link

20171003234 commented Oct 27, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment