DEV Community

Discussion on: WSL Port Forwarding

Collapse
 
timhass6 profile image
Tim Hass • Edited

Great post, thank, this script is very handy until WSL finds a way to do it as built-in or at least provide a way to set "static" ip for the wsl.
after your permission if you will, I just modified your code so it would map host port to different ports on WSL
*don't forget to enable host ports on windows firewall ;)
*install net-tools on wsl , $sudo apt install net-tools

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
Break
}

$remoteip =bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteip -match '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}';

if( $found ){
$connectaddress = $matches[0];
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}

$ports=@(3388,3306);
$connectports=@(3389,3306)

iex "netsh interface portproxy reset";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
$connectport=$connectports[$i];
iex "netsh interface portproxy add v4tov4 listenport=$port connectport=$connectport connectaddress=$connectaddress";
}
iex "netsh interface portproxy show v4tov4";