Windows wsl port forwarding

WSL Port Forwarding

When you start a server in WSL, both Windows and Linux share the same local host. When using a WSL 1 distribution, if your computer was set up to be accessed by your LAN, then applications running in WSL could be accessed on your LAN as well. This isn’t the default case in WSL 2.

So, in order to access the server from your local devices, you need to port forward the WSL local IP using netsh.

First, install net-tools in your linux distro.
For Ubuntu,

Exit fullscreen mode

Next, in Windows, create network.ps1 PowerShell script file with the following content.

Exit fullscreen mode

Note: The network should be a private network.

The script will ask for admin access.

The script gets the WSL IP address and then executes netsh commands to forward the connection to your Windows’ local IP, which you can see by executing ipconfig in either PowerShell or Command Prompt.

The script also resets all previous forwards and at the end displays the list of ipv4 connections forwarded.

You can modify the $ports array with your commonly used ports.

Since WSL2 uses virtual network adapters, its IP address resets after every startup.

For Expo users

Include both ports 19000 and 19001 in the $ports array. (Don’t include 19002 — dev tool server).

In your Android device (connected to the same network as your PC), copy exp:// :19000 to the clipboard.

Open Expo Go, «Open from Clipboard» option will appear.

Notes

  • PowerShell command to reset all forwards

Exit fullscreen mode

  • PowerShell command to view all forwards

Exit fullscreen mode

Have a desktop shortcut for the script. It could be handy.

The network should be a private network.

If your primary purpose is to only check your website for responsive design with your mobile, there is a simple way for that in chrome. See Chrome remote debugging

References

  • Accessing a WSL 2 distribution from your local area network (LAN) — WSL Docs
  • WSL issues on Github
  • This workaround
  • Running a command as Administrator using PowerShell — From StackOverFlow

Discussion (4)

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;
>

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»;

Favorite heart outline button

TLDR: This post is underrated AF, WSL 2 users should save this script up as a gist.

I did not know that this issue exist, spent hours if not days trying to figure why my microservices are not reachable from one app to another.. This code saved my life, now all my services between WSL 2 and windows can communicate perfectly.

Читайте также:  Брандмауэр как отключить windows 10 чтобы не включался

Favorite heart outline button

Thank you the powershell script worked for me. Been trying to get this working for ages

Favorite heart outline button

Hello! Thank you for sharing this. Is there any problem in listening to port 80? I have a Gitlab docker container running on port 80. I ran your script but it is not being reached in my local network

WSL2 not forwarding ports #5439

Comments

dalgibbard commented Jun 18, 2020

Environment

Steps to reproduce

Associated Feedback Hub link: https://aka.ms/AA8qyij

Initially after upgrade to Win 10 20150, my existing WSL2 build was working great.
I unregistered that WSL distro, and on recreating it, I could no longer connect to ports hosted in WSL, from Windows.

I’ve uninstalled the WSL features (including Containers + Hyper-V etc), and the Ubuntu apps that came from the Microsoft Store, and uninstalled VSCode (the application i’m trying to use primarily)

Reinstalled all these, fresh WSL2 install of Ubuntu 20.04. Installed VSCode + the WSL remote extension, and it installs and starts the VS Code server listening on a particular port; but errors that it cannot connect to it.
This port is accessible from within WSL, but not from Windows (eg. browser etc — it responds with a 404 at least in WSL, but ERR_CONNECTION_REFUSED from a browser in windows.)

Expected behavior

WSL should forward ports of running services, to be accessible from Windows (as per previous behaviour).

Actual behavior

Ports opened in WSL are not accessible from Windows.

The text was updated successfully, but these errors were encountered:

ad-on-is commented Jun 19, 2020

I’m on 20150 and no problem here. VSCode Remote and all ports work like they did prior to the update. I didn’t recreate the VM though. Also I’m running Docker Desktop for the web-dev ports.

xddz9 commented Jun 19, 2020 •

Same issue on 19042. I’ve combed through a lot of similar issues here but no one solution seems to fix it for good (including disabling fast refresh and rebooting Ubuntu with wsl —shutdown).

It was working fine for months, then it broke out of nowhere. It randomly works again with some ports, only to stop working altogether minutes later, so it’s really hard to reproduce the problem.

I’ve resorted to this for now.

Microsoft Windows [Version 10.0.19042.330]
Ubuntu 18.04.4 LTS

ad-on-is commented Jun 19, 2020

There was an port-forwading issue a while back, which was got resolved. Just some thoughts. Did you check your firewall settings? Maybe some third-party interferes there?

xddz9 commented Jun 19, 2020

There was an port-forwading issue a while back, which was got resolved. Just some thoughts. Did you check your firewall settings? Maybe some third-party interferes there?

Not a firewall issue for sure. Looking at other open issues it seems like I’m not the only one having this problem still. I apprecciate this sort of thing is pretty complex to debug, so I’m just chiming in to let the devs know it might be worth looking into.

Disclosure: I haven’t tried reinstalling my distro, but I’m running the standard Ubuntu 18 with Node.js to serve a web server on different ports (300x, 500x, 900x). VS Code is running just fine and so is everything else, I just can’t reliably get a web server on Linux to load on Window’s localhost. (Yes, it’s running on 0.0.0.0).
I’m confident it’s not a problem in my app, I’ve tried with a couple generic web servers to no avail, so it’s definitely a networking issue.
I might be doing something terribly wrong on my side, but since it appears to work on an off when rebooting windows/linux, and since other people have reported the same thing, I felt like adding my 2 cents as well.

Читайте также:  Как посмотреть буфер обмена линукс

ad-on-is commented Jun 19, 2020

I’m confident it’s not a problem in my app, I’ve tried with a couple generic web servers to no avail, so it’s definitely a networking issue.

TBH, I’m running everything in Docker containers, NodeJS servers too. This has the benefit that it allows me to test stuff from my smartphone, accessing 192.168.1.100:3000 (Windows PC). And this is a network functionality that WSL2 does not offer, unfortunatelly. Maybe it’s somehow correlated.

Could you test running the servers inside Docker containers?

xddz9 commented Jun 19, 2020 •

This has the benefit that it allows me to test stuff from my smartphone, accessing 192.168.1.100:3000 (Windows PC). And this is a network functionality that WSL2 does not offer, unfortunatelly. Maybe it’s somehow correlated.

That was my use case as well. I actually managed to get it working before, back when localhost forwarding was working properly by running this on PowerShell as admin:

(I got this snippet to work with this solution, but it works only for one port. Maybe related to this issue, which was closed but other people still report as not working)

Worked like a charm with a simple firewall rule on Windows Defender to open those two ports.

I might give Docker a go, but honestly I doubt it will work, and if it’s indeed a networking issue I’m way out of my depth here. Thank you for your comments though! 🙂

Connecting to WSL2 server via local network

I’m developing a rails app using WSL2/Ubuntu on my Windows 10 machine, which is great! The problem is I can’t connect to my server from another computer in the same network.

For further clarity, I am running a Puma server on localhost:3000

I have tried the following:

  1. Directly connecting to the IP address assigned to Ethernet adapter vEthernet (WSL) -> 172.26.208.1:3000
  2. Directly connecting to the host machine’s IPv4 address -> 192.168.0.115
  3. Adding a firewall exception (using Bitdefender)
  4. Binding the IPs above rails s -b 172.26.208.1 -p 3000

None of the above have worked thus far. What I’d like to do is:

  • Test the website on another laptop/tablet/phone
  • Use VScode from another computer

Is there anything I’m missing to at least see the website correctly? (and any comments on the VScode part would be appreciated)

13 Answers 13

See this video, it helped me:

Microsoft has published a little bit of information about this on their WSL1 to WSL2 comparison page

Don’t forget to put feedback after.

Option 1: Use port forwarding

This one worked for me:

The firewall commands in that script didn’t work on my system. So I deactivated the Windows firewall completely and use the following stripped version. (The final users will use a 3d party firewall anyway, so that’s ok).

You may need to «apt install net-tools» for ifconfig in the script. There’s also a solution with «ip addr» in the internet somewhere that does not need ifconfig» in a great thread, I haven’t a link for here and now.

Caveat

This works only for TCP traffic. netsh interface portproxy does not support port forwaarding of UDP traffic.

Option 2: Bridge mode

Solution: Switch from NAT to Bridge mode

WSL2 comes by default in NAT mode. There the wsl2 system has another ip in another subnet than the host. The PC is from external peers only visible by the windows IP and the wsl2 ip/net is hidden/internal. So all traffic would need to be accepted by the windows IP and then forwarded to the wsl2 ip (port forwarding).

There is another mode called bridge mode. In bridge mode your network interface card will be shared to the wsl2 system, and it will get its own IP/Net in wsl2. So in effect your network card is shared to both systems (windows / wsl2) and will have two IPs, as if you’d have two systems with its own network card each. Cool thing: You will never have port conflicts when Windows uses the same port as well, as your wsl2 app (like 111).

Читайте также:  Linux объединить вывод двух команд

Enable bridge mode

Open Hyper-V Manager as administrator

Select your pc, open Virtual Switch Manager

Set to external network

Select the network card the traffic runs through

Then login to wsl2 terminal and configure an IP address. E.g.

You need to use another free IP (not your Windows IP). If your network has a DHCP server your wsl can get one by:

Caveat

I haven’t elaborated yet, how to get DNS working in this scenario in case you want to still be able to access the internet (apt etc.). There’s some documentation from MS written in /etc/resolv.conf and maybe executing what’s written there and installing resolvconf (prior to all steps above, as you have no internet once you start to bridge) might do the trick.

Getting your WSL2 distro to behave like any other client on your network

Building on Roelofs suggestion no.2, here’s what made everything tick in my case. I’m too fresh to just leave a comment unfortunately.

My starting point:
Win 10 Pro
Ubuntu under WSL2
(Docker with Linux containers)

My goal:
Getting an rtmp stream from a client on the network into and back out of an nginx server running on the Ubuntu machine.

Building the bridge

In my case, I could not get Hyper-V to set the bridge up properly. After selecting External network for the WSL switch in the Virtual switch section of Hyper-V Manager and hitting apply, it eventually failed with error 0x80070490. Don’t know why and didn’t have the time to investigate. WSL was not running and neither was the Docker service.

Instead, I just left the setting on Internal network and bridged the interfaces the manual way, under Network Connections (run->ncpa.cpl). In my case, the WiFi connection and vEthernet (WSL). Immediately after doing this, I lost internet connectivity and it took me an embarrassingly long time to find out that a reboot was needed. (Windows for once did not ask me to!)

Getting the VM in shape

After the reboot, I now had internet access from the host, the bridge was set to DHCP and had inherited the IP of the WiFi interface (192.168.1.246). Great.

The VM however was still getting the IP of the virtual switch (or however you want to view it, the random 172.x.x.x address that windows seems to assign to the switch as well as the VM).

Firing up Ubuntu, I decided to do a:

threw a handful of errors at me since I was using the vanilla Ubuntu distro from Windows store, no systemd, no fun. Despite that, it did manage to add the IP of the bridge to eth0. As this was not very handy, I got rid of that with:

but not before taking a sneak peek at the routing table:

After deleting the old IP, I added a unique one from outside of my DHCP range:

I checked the routing table again and the first entry was gone. At this stage I could ping LAN but not WAN.

Added the entry back with:

Pinging WAN IPs was now possible, but no DNS resolution. LMGTFM: Adding permanent DNS In case the solution goes missing, here it is, credit to non-static:

So, to conclude, check your routing and setup your DNS-conf properly. Unfortunately, the IP settings are reverted every time you restart WSL. If you are not ok with doing this manually every time there are discussions on how to automate it here and here. I haven’t had the time to find my favorite.

Оцените статью