Skip to content

Instantly share code, notes, and snippets.

@xmeng1
Created July 14, 2019 06:50
Show Gist options
  • Save xmeng1/aae4b223e9ccc089911ee764928f5486 to your computer and use it in GitHub Desktop.
Save xmeng1/aae4b223e9ccc089911ee764928f5486 to your computer and use it in GitHub Desktop.
WSL2 Port forwarding port to linux
$remoteport = bash.exe -c "ifconfig 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 coma
$ports=@(80,443,10000,3000,5000);
#[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";
}
@khaitranhq
Copy link

@luizwhite you're not alone :)))

@jayagami
Copy link

jayagami commented Jan 9, 2021

you can obtain ip with:

wsl hostname -I

@slaughtering
Copy link

$remoteport to $wsl2_ip maybe better naming?

@wadewadewadewadewadewade

you can obtain ip with:

wsl hostname -I

Am I doing something wrong if I get 172.24.128.1 from wsl hostname -I from Windows, and 172.24.137.181 from ifconfig in WSL2 (Ubuntu)?

@jayagami
Copy link

jayagami commented Apr 6, 2021

you can obtain ip with:

wsl hostname -I

Am I doing something wrong if I get 172.24.128.1 from wsl hostname -I from Windows, and 172.24.137.181 from ifconfig in WSL2 (Ubuntu)?

Well, in my case, wsl hostname -I and ip addr can get the same ip address.

@wadewadewadewadewadewade

Thanks @jayagami!

As it turned out, I had two WSL installs: Legacy and Ubuntu; i was using Ubuntu but Legacy was set to default with I ran wsl --list. I used wsl --set-default "Ubuntu" and that let wsl hostname -I tell me the correct IP!

wojtow helped me in this comment thread: https://superuser.com/questions/1586386/how-to-find-wsl2-machines-ip-address-from-windows/1603307?noredirect=1#comment2502448_1603307

Thanks to both of you though!

@jayagami
Copy link

jayagami commented Apr 6, 2021

Thanks @jayagami!

As it turned out, I had two WSL installs: Legacy and Ubuntu; i was using Ubuntu but Legacy was set to default with I ran wsl --list. I used wsl --set-default "Ubuntu" and that let wsl hostname -I tell me the correct IP!

wojtow helped me in this comment thread: https://superuser.com/questions/1586386/how-to-find-wsl2-machines-ip-address-from-windows/1603307?noredirect=1#comment2502448_1603307

Thanks to both of you though!

You're welcome, glad you have it solved.

@HarryCaveMan
Copy link

HarryCaveMan commented May 5, 2021

The script did not work for me for as is because I have WSL installed for a non-admin user and not for the admin, so I had to run the wsl bash commands as the user with WSL and then pass the values to a process to run as admin and do the firewall bits... This one works if you are in my situation (the sleep is there just so you can see the rule output before the subprocess shell despawns):

$remoteport = wsl hostname -I
$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 coma
$ports=@(3000,5000,8080);

#[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 ",";
Write-Host $ports_a
Write-Host $remoteport
Write-Host $addr

#[Script]
$script = {
  function run([string]$ports_a,[string]$remoteport,[string]$addr){
    #Remove Firewall Exception Rules
    iex \"Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock'\";
    Write-Host $ports_a
    Write-Host $remoteport
    Write-Host $addr
    #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\";
    }
    Start-Sleep -s 25
  }
}
Start-Process -FilePath powershell.exe -ArgumentList "-Command & {$script run '$ports_a' '$remoteport' '$addr'}" -verb RunAs

@rlscode
Copy link

rlscode commented Sep 1, 2021

Thanks, it works for me after run script run "wsl hostname -I " and use the ip in the address for axios

@finalcreator
Copy link

Amazing tips from all guys

@kuhajeyan
Copy link

where should we run this script?

@Esensats
Copy link

Here's a version with better error handling, and with working firewall commands (you have to use $ports directly instead of $ports_a):

try {
	$remoteport = bash.exe -c "ip addr 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{
	  throw "The Script Exited, the ip address of WSL 2 cannot be found";
	}

	#[Ports]

	#All the ports you want to forward separated by a comma (no spaces)
	$ports=@(22,2049);


	#[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
	Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -ErrorAction SilentlyContinue;

	#adding Exception Rules for inbound and outbound Rules
	New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports -Action Allow -Protocol TCP -ErrorAction stop;

	New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports -Action Allow -Protocol TCP -ErrorAction stop;


	for( $i = 0; $i -lt $ports.length; $i++ ){
	  $port = $ports[$i];
	  netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr;
	  netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport;
	}

	echo "For WSL IP $remoteport added Firewall rules and port forwards for ports: $ports_a";
} catch {
    Write-Error $_.Exception.ToString();
    Read-Host -Prompt "The above error occurred. Press Enter to exit.";
}

Add the .ps1 script to task scheduler with elevated rights on PC launch, or create a shortcut to the .ps1 file with elevated rights with this in the object field of the shortcut's properties:

"C:\Program Files\PowerShell\7\pwsh.exe" -f C:\YOUR_OWN_PATH_TO\script.ps1

Change the paths to powershell's executable and to your script accordingly.

@Esensats
Copy link

Also, as far as I am aware here's the original source of the script. A user named edwindijas has to be the original author of the script.

@xinatcg
Copy link

xinatcg commented Feb 26, 2024

Also, as far as I am aware here's the original source of the script. A user named edwindijas has to be the original author of the script.

yeah, i had mentioned it in the comments

https://gist.github.com/xmeng1/aae4b223e9ccc089911ee764928f5486?permalink_comment_id=3342144#gistcomment-3342144

@edwindijas
Copy link

@Esensats great work.

@LennDG
Copy link

LennDG commented Apr 12, 2024

This is probably user error, but after executing this script I am no longer able to use my browser on Windows to reach a server running on 127.0.0.1 in WSL. I also cannot reach it through the IP associated with WSL in ipconfig.

Basically I am now further from the original goal as I was. Not only can I not reach the server from another device, I also cannot reach it from the windows machine running WSL itself.

This has also persisted after removing the Firewall rules. At this point I don't even know how to fix this problem. Turning off the firewall entirely has also not fixed this, so there must be a different issue at play than the firewall...

Remote Development in VSCode also has stopped working, likely due to the same issue. Somehow this script (or more likely, Windows itself) has completely broken WSL.

Even after completely reinstall WSL I now cannot reach it in anyway from the host machine, except by opening it in a terminal. I would advise anyone to reconsider using this script. I don't know what exactly about it has caused this, but it has completely bricked my system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment