Last active
June 12, 2025 21:59
-
-
Save kendallroth/1f4871febffa0577338214f58673cc1a to your computer and use it in GitHub Desktop.
Forward WSL2 ports to host
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Forward WSL2 ports to host machine/platform (handles Windows Firewall) | |
# | |
# NOTE: 'iex' is a shortform for 'Invoke-Expression' | |
# Ports that should be forwarded to WSL2 and allowed through firewall (comma-separated) | |
$ports = @(8081); | |
# WSL IP address changes whenever WSL restarts | |
$wsl_ip = $(wsl hostname -I).Trim(); | |
# Incoming requests from any IP should be matched | |
$listen_all_ips = '0.0.0.0'; | |
if ( -Not $wsl_ip ) { | |
Write-Output "IP address for WSL 2 cannot be found"; | |
exit; | |
} | |
Write-Output "WSL IP: '$wsl_ip'"; | |
### Windows Firewall ##### | |
$firewall_rule = "WSL2 Forwarded Ports"; | |
$firewall_ports = $ports -join ","; | |
# Remove existing firewal rule (will error if not already present; can ignore) | |
iex "Remove-NetFireWallRule -DisplayName '$firewall_rule' "; | |
# Allow Expo ports through Windows Firewall | |
iex "New-NetFireWallRule -DisplayName '$firewall_rule' -Direction Inbound -LocalPort $firewall_ports -Action Allow -Protocol TCP;" | |
iex "New-NetFireWallRule -DisplayName '$firewall_rule' -Direction Outbound -LocalPort $firewall_ports -Action Allow -Protocol TCP;" | |
### WSL Port Proxy ##### | |
# Show all previously proxied ports | |
iex "netsh interface portproxy show v4tov4" | |
# Configure port forwarding (via remove/add) | |
for ( $i = 0; $i -lt $ports.length; $i++ ) { | |
$port = $ports[$i]; | |
# Remove previously proxied port | |
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$listen_all_ips" | |
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$listen_all_ips connectport=$port connectaddress=$wsl_ip" | |
} | |
# Show all newly proxied ports | |
iex "netsh interface portproxy show v4tov4" | |
cmd /c pause |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leaving this here to save someone...
As I had docker configured on my wsl I got 2 ip addresses (check them by running
ip addr
in your wsl terminal)found after line
9
run$wsl_ip = $(wsl hostname -I).Trim();
.After command execution log from line
19
looked like this:WSL IP: '172.19.222.216 172.17.0.1'
, which prevented script from working properly and my phone connecting successfully to my windows ip.After running
ip addr
and checking that my wsl ip is in fact172.19.222.216
,fix was to simply change line
9
from$wsl_ip = $(wsl hostname -I).Trim();
to$wsl_ip = $(wsl hostname -I).Trim().Split(' ')[0];
.