Guest User

WSL Port Forwarding by John Wright

a guest
Jul 1st, 2023
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 1.02 KB | Source Code | 0 0
  1. $ports = @(80, 443, 10000, 3000, 5000);
  2.  
  3. $wslAddress = bash.exe -c "ip addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'";
  4.  
  5. if ($wslAddress -match '^(\d{1,3}\.){3}\d{1,3}$') {
  6.   Write-Host "WSL IP address: $wslAddress" -ForegroundColor Green;
  7.   Write-Host "Ports: $ports" -ForegroundColor Green;
  8. }
  9. else {
  10.   Write-Host "Error: Could not find WSL IP address." -ForegroundColor Red;
  11.   exit;
  12. }
  13.  
  14. $listenAddress = '0.0.0.0';
  15.  
  16. foreach ($port in $ports) {
  17.   netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$listenAddress;
  18.   netsh interface portproxy add v4tov4 listenport=$port listenaddress=$listenAddress connectport=$port connectaddress=$wslAddress;
  19. }
  20.  
  21. $fireWallDisplayName = 'WSL Port Forwarding';
  22.  
  23. Remove-NetFireWallRule -DisplayName $fireWallDisplayName;
  24. New-NetFireWallRule -DisplayName $fireWallDisplayName -Direction Outbound -LocalPort $ports -Action Allow -Protocol TCP;
  25. New-NetFireWallRule -DisplayName $fireWallDisplayName -Direction Inbound -LocalPort $ports -Action Allow -Protocol TCP;
Advertisement
Add Comment
Please, Sign In to add comment