Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Last active May 20, 2022 01:25
Show Gist options
  • Save hongymagic/518ac8cf858923176ed1ceb0ca8a46ba to your computer and use it in GitHub Desktop.
Save hongymagic/518ac8cf858923176ed1ceb0ca8a46ba to your computer and use it in GitHub Desktop.
Setup port forwarding from host to WSL 2

How to use it

  1. Download the above script
  2. Place it somewhere in your drive
  3. The run it
Setup-WSL-Port-Forwarding.ps1

NOTE: Tested on a machine with a single distro. May need to change the wsl hostname -I command to grab your desired distro's IP

<#
.Description
Setup-WSL-Port-Forwarding function forwards commonly used ports from host to WSL.
The forwarded ports include standard HTTP, HTTPS, Postgres, Redis and other development ports.
#>
$PortsToForward = @(80, 443, 3000, 3001, 5000, 8080, 8081, 8888, 9090, 9091, 9190, 9191, 5432, 6379)
$DestinationIP4Address = (wsl hostname -I) -join "`n"
function ForwardPort([int]$port, [string]$ip) {
Write-Output ("Forwarding 0.0.0.0:$port to " + ($ip.Trim()) + ":" + $port)
netsh.exe interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=($ip.Trim())
}
Write-Host "Setting up port forwarding for from host -> WSL2 network interface $DestinationIP4Address"
foreach ($port in $PortsToForward) {
ForwardPort $port $DestinationIP4Address
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment