Network problems using WSL2
My answer is based on the article Running a public server from WSL 2, where the theory is that Windows creates a virtual adapter that isn’t properly bridged with the internet network adapter.
The article raises the following points:
-
In WSL ensure that your server is using IPv4
-
If you are using a firewall in WSL, allow the relevant port (3390)
-
In Windows, forward your port from the public IP port to the WSL port in Command Prompt or Powershell with admin rights:
netsh interface portproxy add v4tov4 listenport=$PORT listenaddress=0.0.0.0 connectport=$PORT connectaddress=127.0.0.1
-
In Windows, allow the port through the Windows firewall using a new Inbound Rule.
-
For access from the internet, setup port forwarding for the port in the router.
A YouTube video describing the process with some small differences is WSL 2 Networking.
I needed three things for this to work:
- Upgrade to the latest version of windows
wsl --shutdown
- Settings > Network & Internet > Network Reset as described here
I ran into this as well; this is my solution: WSL2-PortForward.cmd
It takes care of the port proxy and firewall rules for you and cleans up after itself.
@ECHO OFF
SET LXDISTRO=MyWSL2vm & SET WSL2PORT=3399 & SET HOSTPORT=3398
NETSH INTERFACE PORTPROXY RESET & NETSH AdvFirewall Firewall delete rule name="%LXDISTRO% Port Forward" > NUL
WSL -d %LXDISTRO% -- ip addr show eth0 ^| grep -oP '(?^<=inet\s)\d+(\.\d+){3}' > IP.TMP
SET /p IP=<IP.TMP
NETSH INTERFACE PORTPROXY ADD v4tov4 listenport=%HOSTPORT% listenaddress=0.0.0.0 connectport=%WSL2PORT% connectaddress=%IP%
NETSH AdvFirewall Firewall add rule name="%LXDISTRO% Port Forward" dir=in action=allow protocol=TCP localport=%HOSTPORT% > NUL
ECHO WSL2 Virtual Machine %IP%:%WSL2PORT%now accepting traffic on %COMPUTERNAME%:%HOSTPORT%
Run the command:
.\WSL2-PortForward.cmd
Result:
WSL2 Virtual Machine 172.17.109.95:3399 now accepting traffic on MYCOMPUTER:3398