Skip to content

Instantly share code, notes, and snippets.

@airtonix
Created January 8, 2024 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airtonix/3ef5bdc63a2a47942bdf046383a95ba4 to your computer and use it in GitHub Desktop.
Save airtonix/3ef5bdc63a2a47942bdf046383a95ba4 to your computer and use it in GitHub Desktop.
Portforward one or more ports to WSL2

Enable portforwarding for one or more wsl2 ports

chuck these two files in your homedir at

~/Documents/Powershell/Microsoft.PowerShell_profile.ps1
~/Documents/Powershell/bin/Start-Wsl2PortForward.ps1

Protip: Install sudo for windows

winget install gerardog.gsudo

Enable some ports:

sudo Start-Wsl2PortForward.ps1 -Ports 3060,8080,3000
#
# ~/Documents/Powershell/Microsoft.PowerShell_profile.ps1
#
# get reference to the profile file dir
$HEREDIR = Split-Path -Parent $MyInvocation.MyCommand.Path
# add this directory/bin
$env:PATH += ";${HEREDIR}\bin"
#
# ~/Documents/Powershell/bin/Start-Wsl2PortForward.ps1
#
param(
[Parameter(Mandatory = $true)]
[string[]]$Ports
)
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
Write-Warning "This script needs to be run as an administrator."
Break
}
$address =wsl -- ip -o -4 -json addr list eth0 `
| ConvertFrom-Json `
| %{ $_.addr_info.local } `
| ?{ $_ }
$found = $address -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if ( !$found ) {
Write-Output "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
$address = $matches[0];
Invoke-Expression "netsh interface portproxy reset";
for ( $i = 0; $i -lt $Ports.Length; $i++ ) {
$port = $Ports[$i];
# port forward
Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$address";
# allow firewall access
Invoke-Expression "netsh advfirewall firewall add rule name='WSL2 Port Proxy ${port}' dir=in action=allow protocol=TCP localport=$port";
}
Invoke-Expression "netsh interface portproxy show v4tov4";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment