Skip to content

Instantly share code, notes, and snippets.

@Steakeye
Last active September 24, 2024 18:42
Show Gist options
  • Save Steakeye/31851ad2289c70b72ad9817cf3ec1c42 to your computer and use it in GitHub Desktop.
Save Steakeye/31851ad2289c70b72ad9817cf3ec1c42 to your computer and use it in GitHub Desktop.
Sharing WSL2 hosted server with host LAN
param(
[Parameter(Position=0,mandatory=$true)][String] $port
)
echo "Enabling port in firewall..."
echo "Port $port"
netsh advfirewall firewall add rule name="Open Port $port" dir=in action=allow protocol=TCP localport=$port
param(
[Parameter(Position=0,mandatory=$true)][String] $port,
[String] $guestIP
)
$guestIP = if ($guestIP) { $guestIP } else { wsl hostname -I }
echo "Setting up port forwarding..."
echo "Forwarding port $port to $guestIP"
netsh interface portproxy add v4tov4 listenport=$port listenaddress=0.0.0.0 connectport=$port connectaddress=$guestIP
echo "Displaying port forwarding table"
netsh interface portproxy show all

Sharing WSL2 hosted server with host LAN

This gist describes what needs to be done so a server running inside a WSL context can be accessed by devices on the network of the host device.

It's quite likely that the commands needed to be run will require admin rights, so you will need to have been given at least Local Admin privileges on your machine and then run Powershell as Administrator.

Port forwarding

In order for other devices on you local network to find the server on your linux subsystem, you need to set up port forwarding so requests made to your host machine will be passed to the linux vm. The WSL instance will have its own IP which you can get by running wsl hostname -I.

Then use forward-port-to-wsl2.ps1 <port_to_forward> -guestIP <wsl_ip>, where port_to_forward is the port you want to pass-through and wsl_ip is the IP found for your WSL instance.

Enabling port on host firewall

You also need to explicitly set your Windows firewall to allow the ports used by your WSL servers to be exposed. To do this run firewall-enable-port.ps1 <port_to_enable>.

If you want to confirm that you have enabled this port in the firewall you can run Get-NetFirewallRule -Direction Inbound -Enabled True .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment