Skip to content

Instantly share code, notes, and snippets.

@IAmStoxe
Created August 28, 2024 22:42
Show Gist options
  • Save IAmStoxe/74e5c6c3a697c0392d6ec7586e28e91b to your computer and use it in GitHub Desktop.
Save IAmStoxe/74e5c6c3a697c0392d6ec7586e28e91b to your computer and use it in GitHub Desktop.
Forward port to WSL
# Define variables
$port = 80
$wslIp = (wsl hostname -I | ForEach-Object { $_.Split(" ")[0] }).Trim() # Get the first IP address of the WSL instance
$firewallRuleName = "AllowPort$portToWSL"
$netshRuleName = "WSL Port Forwarding $port"
# Add a firewall rule to allow inbound traffic on the specified port
Write-Host "Adding firewall rule to allow inbound traffic on port $port..."
New-NetFirewallRule -DisplayName $firewallRuleName -Direction Inbound -LocalPort $port -Protocol TCP -Action Allow
# Ensure the firewall is open for the specified port
Write-Host "Opening Windows Firewall for port $port..."
netsh advfirewall firewall add rule name="$firewallRuleName" dir=in action=allow protocol=TCP localport=$port
# Set up port forwarding from the Windows host to the WSL instance
Write-Host "Setting up port forwarding from port $port to WSL IP $wslIp..."
netsh interface portproxy add v4tov4 listenport=$port listenaddress=0.0.0.0 connectport=$port connectaddress=$wslIp
Write-Host "Port forwarding setup complete."
# Verify the port forwarding rule
Write-Host "Current port forwarding rules:"
netsh interface portproxy show v4tov4
# End of script
Write-Host "Script execution complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment