WSL 2 requires some extra work as compared to WSL 1.
Allow the required port(s) through the firewall.
1.1 Launch Windows Defender Firewall with Advanced Security
1.2 On the left pane select Incoming Rules
.
1.3 On the right pane click on New Rule
.
1.4 For the rule type select Port
. Next.
1.5 Select TCP
and Specific local ports
. Insert the port, a comma-separated list of ports or a port range. Next.
1.6 Select Allow connection
. Next.
1.7 Check only the Public
profile. Next.
1.8 Enter a name for the rule. e.g. WSL
. Done.
Find out the IP Address of WSL from within it:
grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'
This is the IPv4 Address of the Network Interface vEthernet (WSL)
.
Test the connection to the Windows host using curl
or telnet
:
3.1 curl ip.from.step.2:port
I have used this procedure to connect to an Oracle server and an X server running on Windows.
Update: Since the IP Address of WSL will change every time Windows is restarted, it is convenient to automatically fetch it and update the hosts
file.
In WSL:
execute cat /etc/hosts
to find out the name of the Windows host.
Add the following code to ~/.profile
:
HOST=<WINDOWS_HOSTNAME>
IP_HOST=$(grep -m 1 $HOST /etc/hosts)
OLD_IP=$(echo "$IP_HOST" | awk '{print $1}')
NEW_IP=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}')
if [ "$NEW_IP" != "$OLD_IP" ]; then
echo "Updating IP Address-hostname mapping"
sudo sed -i "s|$IP_HOST|$NEW_IP\t$HOST|" /etc/hosts
echo "$HOST has the IP Address $NEW_IP"
fi