Skip to content

Instantly share code, notes, and snippets.

@thomaswilley
Last active January 30, 2021 18:04
Show Gist options
  • Save thomaswilley/e040fbacc2124528f5becb53bf7bb54f to your computer and use it in GitHub Desktop.
Save thomaswilley/e040fbacc2124528f5becb53bf7bb54f to your computer and use it in GitHub Desktop.
# WSL2_PORT_FORWARDING.ps1
# This script created by Brian Ketelsen (https://www.brianketelsen.com/blog/ssh-to-wsl2/
# and trivially patched by Thomas Willey 12/2020
# PURPOSE: Enable local development in WSL2 and expose webservers/services over IP from w/in WSL2 to local network of windows machine
# Use example scenario:
# 1. open WSL2, start server (e.g., python3 http.server 0.0.0.0:8000), and try to visit from win machine (e.g., http://localhost:8000) - notice it fails to resolve.
# 2. open powershell as administrator and run this script
# 3. refresh the page on your win machine's browser (http://localhost:8000) and see that it loads up.
# 4. bonus: mDNS should work. So you can access from e.g., your phone on local wifi to http://<windows hostname>.local:8000
$remoteport = bash.exe -c "ip address show eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport = $matches[0];
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
#[Ports]
#All the ports you want to forward separated by comma
$ports=@(5000,8000);
#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";
#Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";
#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment