The networking subsystem in WSL2 is different than the used in WSL1. You must consider the differences to access networking apps running on Windows and on Linux:
- In WSL1, Linux uses the same IP addresses than the Windows host, then, you can access the applications using
localhost
or127.0.0.1
- In WSL2, Linux runs on a lightweight virtual machine and has a different IP address. To access networking apps running on the Windows Host you must use the Windows IP address.
Checking the IP address of the Windows host
There are many ways to determine the IP addresses in the Windows host. You may run the following commands in your WSL Linux:
cat /etc/resolv.conf
shows the IP address of theeth0
interface in Windowsipconfig.exe
shows the all the IP configuration in the Windows hostroute.exe print
shows the network routing configuration in the Windows host
Setting the DISPLAY variable for WSL2
Based on the Microsoft documentation, you may set the DISPLAY variable checking the nameserver
in the /etc/resolv.conf
file. (@fqquiner and @VPraharsha already mentioned this)
export DISPLAY=$(grep nameserver /etc/resolv.conf | awk '{print $2}'):0.0
However, I had problems using this solution, probably because I use my notebook with a WiFi connection and multiple virtual networks. Instead of the previous solution, I determine the Windows IP address using route.exe
and checking the interface used in the default gateway.
export DISPLAY=$(route.exe print | grep 0.0.0.0 | head -1 | awk '{print $4}'):0.0
Setting the DISPLAY variable in the .profile
You may set the DISPLAY variable in your ~/.profile
file. I used the following code:
# set DISPLAY to use X terminal in WSL
# in WSL2 the localhost and network interfaces are not the same than windows
if grep -q WSL2 /proc/version; then
# execute route.exe in the windows to determine its IP address
DISPLAY=$(route.exe print | grep 0.0.0.0 | head -1 | awk '{print $4}'):0.0
else
# In WSL1 the DISPLAY can be the localhost address
if grep -q icrosoft /proc/version; then
DISPLAY=127.0.0.1:0.0
fi
fi