loading...

WSL Port Forwarding

vishnumohanrk profile image Vishnumohan R K Updated on ・2 min read

When you start a server in WSL, both windows and linux share the same local host, however your WSL local IP is shared only with windows and cannot be accessed within your local network. This was possible in WSL1, but not with WSL2.

So, in order to access the server from you local devices, you need to port forward the WSL local IP using netsh.

Create network.ps1 powershell script file with the following content in any directory.

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{   
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}

$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';

if( $found ){
  $remoteport = $matches[0];
} else{
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

$ports=@(3000, 3001, 3002, 5500, 19000, 19001);

iex "netsh interface portproxy reset";
for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$remoteport";
}
iex "netsh interface portproxy show v4tov4";

The script will ask for admin access.

The script gets the WSL IP address and then executes netsh commands to forward the connection to your Windows' local IP, which you can see by executing ipconfig in either powershell or cmd prompt or at your router's admin page.

The script also resets all previous forwards and at the end displays the list of ipv4 connections forwarded.

You can modify the ports array with your commonly used ports.

Since WSL2 uses virtual network adapters, its IP address resets after every startup. So you need to run the script every time at startup. To do so, create a script.cmd with contents as follows

powershell <absolute path to the above powershell script>

Put this file in this directory.

C:\Users\<user name>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Now at every startup, windows will automatically forward all your WSL connections running on the mentioned ports to your Windows local IP with the same port, so that you can visit the application across your local network.

Notes

  • Run this command (in Powershell, as admin)
netsh interface portproxy reset

to reset all forwards

  • Run this command (in Powershell, as admin)
netsh interface portproxy show v4tov4

to view all ipv4 forwards.

  • Save network.ps1 in Windows file system.

  • Have a desktop shortcut for the script. It maybe handy.

References

Posted on by:

vishnumohanrk profile

Vishnumohan R K

@vishnumohanrk

Love writing code with JavaScript . IOT Enthusiast.

Discussion

markdown guide