Skip to content

Instantly share code, notes, and snippets.

@twinbird
Created May 16, 2023 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twinbird/57d0b79f5765a8cc1e72305d1f16482d to your computer and use it in GitHub Desktop.
Save twinbird/57d0b79f5765a8cc1e72305d1f16482d to your computer and use it in GitHub Desktop.
Port forwarding to WSL2 from windows host
<#
.SYNOPSIS
Port forwarding from Windows Host environment to WSL2 environment.
.DESCRIPTION
A simple wrapper windows command 'netsh'.
Requires administrator privileges to run.
.PARAMETER FromPort
Specifies the port in the Windows Host environment for port forwarding.
(default: 8080)
.PARAMETER ToPort
Specifies the port of the WSL2 environment to be port forwarded.
(default: 8080)
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PS> .\wsl_port_forward.ps1 -fromport 8080 -toport 3000
#>
Param($FromPort=8080, $ToPort=8080)
# get WSL2 ip addr
$WSL2_IPV4=bash -c 'ip address show eth0 | awk ''/inet / {print \$2}'' | awk -F / ''{print \$1}'''
$WSL2_IPV4=$WSL2_IPV4.TrimEnd()
# get windows host ip addr
$HOST_IPV4=get-netipaddress | where{$_.AddressFamily -eq "IPv4" -and $_.IPAddress -match "192.168." -and $_.PrefixOrigin -eq "Dhcp"} | select -ExpandProperty IPAddress
$HOST_IPV4=$HOST_IPV4.TrimEnd()
# add new portproxy
netsh interface portproxy add v4tov4 listenaddress=$HOST_IPV4 listenport=$FromPort connectaddress=$WSL2_IPV4 connectport=$ToPort
echo "portproxy is enabled(From: ${HOST_IPV4}:$FromPort To: ${WSL2_IPV4}:$ToPort)"
pause
# remove port portproxy
netsh interface portproxy delete v4tov4 listenport=$ToPort listenaddress=$HOST_IPV4
echo "portproxy is disabled"
echo "check current forwarding list: netsh interface portproxy show all"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment