Created
January 26, 2024 13:15
-
-
Save rwunsch/88c667c775c75eec2ab72f50c4ca8a19 to your computer and use it in GitHub Desktop.
Bridge external Ports on Windows into WSL2 - Bridge-WslPorts.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## https://jwstanly.com/blog/article/Port+Forwarding+WSL+2+to+Your+LAN/ | |
## Execute with: powershell.exe -File "C:\Users\wunsch\Bridge-WslPorts.ps1" | |
Start-Transcript -Path "C:\Users\wunsch\Bridge-WslPorts.log" -Append | |
$ports = @(80, 443, 1234, 3000, 4502, 4503, 4326, 4327, 5000, 10000, 25565, 25575); | |
$wslAddress = bash.exe -c "ifconfig eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'" | |
if ($wslAddress -match '^(\d{1,3}\.){3}\d{1,3}$') { | |
Write-Host "WSL IP address: $wslAddress" -ForegroundColor Green | |
Write-Host "Ports: $ports" -ForegroundColor Green | |
} | |
else { | |
Write-Host "Error: Could not find WSL IP address." -ForegroundColor Red | |
exit | |
} | |
$listenAddress = '0.0.0.0'; | |
foreach ($port in $ports) { | |
Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$listenAddress"; | |
Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$listenAddress connectport=$port connectaddress=$wslAddress"; | |
} | |
$fireWallDisplayName = 'WSL Port Forwarding'; | |
$portsStr = $ports -join ","; | |
Invoke-Expression "Remove-NetFireWallRule -DisplayName '$fireWallDisplayName'"; | |
Invoke-Expression "New-NetFireWallRule -DisplayName '$fireWallDisplayName' -Direction Outbound -LocalPort $portsStr -Action Allow -Protocol TCP"; | |
Invoke-Expression "New-NetFireWallRule -DisplayName '$fireWallDisplayName' -Direction Inbound -LocalPort $portsStr -Action Allow -Protocol TCP"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment