Skip to content

Instantly share code, notes, and snippets.

@amorev
Last active June 9, 2022 14:55
Embed
What would you like to do?
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