Access a localhost running in Windows from inside WSL2?

Ganesh A.S picture Ganesh A.S · Nov 10, 2020 · Viewed 9.5k times · Source

I am running a local AEM server in my Windows machine. The server is running on localhost:4502. I am using Ubuntu distro running in WSL2 for my development. I want to access the localhost:4502 running in the Windows machine in my WSL2 Ubuntu.

Is there any way to do that or is it not possible ?

Answer

Tarun Kumar picture Tarun Kumar · Jun 23, 2021

I was also looking for some solution to do this but currently, there is no such option available. Check out this GitHub issue:

https://github.com/microsoft/WSL/issues/4619

One solution can be this:

If you have the IP of windows(host) then it will do the job but the only problem is that IP will change every time. But, WSL2 stores your windows(host) IP in /etc/resolv.conf file. So we can modify our etc/hosts to map winhost to the IP dynamically.

Add the following lines at the end of ~/.bashrc file. This will grep the IP and modify the etc/hosts when you boot the WSL.

export winhost=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
if [ ! -n "$(grep -P "[[:space:]]winhost" /etc/hosts)" ]; then
        printf "%s\t%s\n" "$winhost" "winhost" | sudo tee -a "/etc/hosts"
fi

then run the following command to reload the changes.

$ source ~/.bashrc

now you can use winhost instead of localhost in WSL2(client) to access the servers running windows(host). In your case, it will be winhost:4502 but this will work for any other use cases as well like accessing Postgres/MySQL server running on windows, etc.

NOTE: Always remember to configure your firewall on windows to allow those ports so that WSL2 can access otherwise your connection may get blocked by firewall.