Skip to content

Instantly share code, notes, and snippets.

@kongdd
Last active March 25, 2020 05:42
Show Gist options
  • Save kongdd/78f6e106a805433a23713add73ee9865 to your computer and use it in GitHub Desktop.
Save kongdd/78f6e106a805433a23713add73ee9865 to your computer and use it in GitHub Desktop.
wsl2 static ip best solution

A improved solution based that of @edwindijas:

Known that localhost (and 127.0.0.1) works in the lastest wsl2. Hence the only thing need to do is mapping 127.0.0.1:port to 0.0.0.0:port.

Make sure you can run powershell script

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Execute the following PowerShell scripts in Administrator mode one time can solve the problem. Needn't autostart and execute every time when login.

## Execute in Powershell Administrator mode
#! powershell
#  @author: 
#  1. edwindijas, https://github.com/microsoft/WSL/issues/4150#issuecomment-504209723
#  2. Dongdong Kong, 2020-03-25 ---------------------------------------------------
#All the ports you want to forward separated by coma
$ports=@(23,80,443,8787);

#[Static ip]
#You can change the addr to your ip config to listen to a specific address
# $addr='0.0.0.0';
$addr='0.0.0.0';
$remoteport='127.0.0.1';

$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