Skip to content

Instantly share code, notes, and snippets.

@amorev
Last active March 27, 2024 00:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amorev/785d00a53e2e38cdb24742613daa74e2 to your computer and use it in GitHub Desktop.
Save amorev/785d00a53e2e38cdb24742613daa74e2 to your computer and use it in GitHub Desktop.
WSL add Windows host address to /etc/hosts

This small gist will add automaticaly wsl.host to hosts file and you will be able to communicate with your windows system, using wsl.host as address.

After creating your wsl do next:

  1. Place startup.sh at /startup.sh and run chmod +x /startup.sh
  2. Run visudo
  3. Add %sudo ALL=NOPASSWD: /startup.sh to end of file
  4. Add sudo /startup.sh at end of file /etc/profile

That's all. After first login in wsl after system start wsl.host will point to your windows host

Inspired by https://gist.github.com/irazasyed/a7b0a079e7727a4315b9

#!/usr/bin/env bash
hostsFile="/etc/hosts"
hostname="wsl.host"
ip=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}')
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
remove() {
if [ -n "$(grep -P "[[:space:]]$hostname" /etc/hosts)" ]; then
try sudo sed -ie "/[[:space:]]$hostname/d" "$hostsFile";
fi
}
add() {
if ! [ -n "$(grep -P "[[:space:]]$hostname" /etc/hosts)" ]; then
try printf "%s\t%s\n" "$ip" "$hostname" | sudo tee -a "$hostsFile" > /dev/null;
fi
}
remove
add
@elmys
Copy link

elmys commented Mar 4, 2021

It is not working on my WSL, until manual launch sh-script.

@amorev
Copy link
Author

amorev commented Mar 4, 2021

It is not working on my WSL, until manual launch sh-script.

Any errors in terminal?

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