Skip to content

Instantly share code, notes, and snippets.

@toryano0820
Last active April 24, 2024 19:23
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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
@dabajabaza
Copy link

Thanks, it helps me a lot!

@toryano0820
Copy link
Author

toryano0820 commented Dec 28, 2020

Thanks, it helps me a lot!

My pleasure 😃

@devcharlie
Copy link

devcharlie commented May 18, 2021

Nice work, would be nice if it also adds the following to the /etc/wsl.conf file to prevent the host changes being overwritten everytime it boots up
`[network]

generateHosts = false`

@renato04
Copy link

Thank you!
After 2 hours searching for the solution I found it here!

@20171003234
Copy link

Thank you ! It helps me a lot~!!!~~!

@antman94
Copy link

Should I download the file or how do I run it?

@renato04
Copy link

@Anthel you can create a file with the script like this

> nano mapscript.sh

Paste the script press ctrl+x and y

> chmod +x mapscript.sh
>./mapscript.sh

@tummalah
Copy link

thank you, saved an hour researching on how to map wsl2 to windows localhost

@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