Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WSL 2] WSL 2 cannot access windows service via localhost:port #4619

Open
Tracked by #11025
hzhangxyz opened this issue Oct 25, 2019 · 140 comments
Open
Tracked by #11025

[WSL 2] WSL 2 cannot access windows service via localhost:port #4619

hzhangxyz opened this issue Oct 25, 2019 · 140 comments
Labels
feature wsl2 Issue/feature applies to WSL 2

Comments

@hzhangxyz
Copy link

hzhangxyz commented Oct 25, 2019

Is your feature request related to a problem? Please describe.
although now windows can access wsl service with localhost:port via "localhostForwarding", but wsl cannot access windows service via localhost:port, please fix it, Thank you.

Describe the solution you'd like
When WSL 2 try to connect to localhost:port and be refused, try to connect to windows again.

@hzhangxyz hzhangxyz changed the title [WSL 2] WSL 2 cannot access windows service with localhost:port [WSL 2] WSL 2 cannot access windows service via localhost:port Oct 25, 2019
@craigloewen-msft craigloewen-msft added the wsl2 Issue/feature applies to WSL 2 label Dec 9, 2019
@numeric-lee
Copy link

I was able to use graphic applications in WSL using XMING and Export DISPLAY=:0.0

However, once I upgraded to WSL2 and switching to Export DISPLAY = 172.28.801:0 (my host#) it failed to connect

Things tried:

downloading VcXsrv
switching to another graphics application
running vcxsrv -ac from bash (command not recognized)
running vcxsrv -ac from powershell (command not recognized)
turning firewall off
My Windows 10 build: 19041.1

Here is a typical error message

QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-lw' qt.qpa.screen: QXcbConnection:
Authorization required, but no authorization protocol specified
Could not connect to any X display.

In #4106 you advise to run "vcxsrv -ac" from the bash command line and at least one user accepted that as a solution. I downloaded vcxsrv.exe from sourceforge as an .exe outside of bash, and I see no way to execute it from bash

Many thanks

@gx761
Copy link

gx761 commented Feb 20, 2020

is there any update?

@numeric-lee
Copy link

solved #4793 (comment)

@fquinner
Copy link

fquinner commented Feb 28, 2020

@numeric-lee that's not really solved - that's a workaround. In WSL1 you could hit:

localhost:port

From the WSL environment and that would access the windows service directly without having to:

  • Script extraction of a magic IP address
  • Disable a firewall interface which freaks people (including me) out and doesn't persist on reboot

Use cases are common including:

  • X11 Service running on windows host
  • Shared database access like postgres
  • Access docker on windows host from WSL client

A different IP address, I could live with, though I would suggest that WSL should expose it via WSL_HOST or something like it does for WSL_DISTRO_NAME, but the firewall thing is a big pain point for me. There are a lot of quite similar issues but I'm hoping this is now the central one that will get done, ideally before this gets widespread release.

@Uzume
Copy link

Uzume commented Feb 28, 2020

This is because despite the name (WSL=Windows Subsystem for Linux), WSL2 is not a Windows subsystem like WSL1 and Interix were. WSL2 is a lightweight Hyper-V-based virtual machine with its own separate network interfaces, IP addresses, etc. Localhost and 127.0.0.1 are host local references and having more than one host, they refer to different things in Windows host and Linux guest host.

WSL2 already supplies some sort of special casing including accessing the Linux guest console/login for Windows terminal access to the Linux guest and means of accessing both the Windows host and Linux guest filesystems from both sides ("9p" Linux mounts vs. IFS redirector and UNC "\wsl$"). The best solution would be to generalize this to allow a configured list of port forwarding options. Then one could forward the server socket to the Linux guest allowing the guest to then believe and refer to the server as if it were local to the Linux guest host. For security and performance reasons, it would be good to use virtual machine specific socket system like that used by wslbridge2 (hvsocket).

Another possibly simpler solution would be to come up with something that uses WSL_INTEROP sockets to create a generalized tunneling solution. I am not sure how stable they are though as they seem to depend on WSL sessions (perhaps a Windows service that opens a WSL session and sets up all the configured tunneling and then keeps the session open).

@andreialecu
Copy link

andreialecu commented Mar 10, 2020

To anyone needing a workaround, run this on the Windows side:

adb -a -P 5037 nodaemon server

and this on WSL2:

adb kill-server
export ADB_SERVER_SOCKET=tcp:192.168.100.5:5037
adb devices

Replace the IP with your windows IP.

Edit: I may have commented on the wrong issue. It was one on the same error but related to Android studio.

@raelmax
Copy link

raelmax commented Mar 10, 2020

To workaround this on selenium+chromedriver, I´m running a socat on wsl2 relaying requests to localhost:port to windows-host:port. This workaround can be used in a lot of other cases. :)

@jordaofranca
Copy link

jordaofranca commented Mar 16, 2020

Every time that I go back to wsl2 and give it a try, the same happens again. After updating windows, I'm not able to access localhost:port. Not event using wsl internal ip:port. Looks like it is a recurrent problem. Why we need to face it every update?

@Uzume
Copy link

Uzume commented Mar 16, 2020

@andreialecu That only works for one particular service related to Android Debug Bridge.

@raelmax Yes, that is sort of what I suggesting by my comment about using WSL interop sockets. I had envisioned something with ncat (from nmap) but netcat and socat probably can also work. I thought about ncat because there should be both Windows and Linux versions available (sadly Windows Security identifies this as a "hacker tool" potential threat and quarantines it unless specifically allowed) so it was not too big of a stretch to just use pipes and depend on WSL interop to allow such to automatically cross the host-guest boundary.

What commands are you using? How do you handle the Windows host side of things? Which Linux distribution are you using that has socat or did you compile that yourself? Providing the commands you are using would be helpful. Thank you.

@jordaofranca I believe WSL1 is still available in later versions of Windows 10 but you do need to set the WSL version for each distribution (and you can set the default version for new distributions too). Obviously moving back to WSL1 is also just a workaround and not a solution.

@raelmax
Copy link

raelmax commented Mar 19, 2020

@Uzume I´m using Ubuntu 18.04 and I´ve installed socat via apt-get. :)

My use case is as follow:

  • I need to use chromedriver(and chrome) running on Windows(host) and I need to control the chromedriver via selenium running on my Ubuntu(via wsl2).

Since I can´t update my code to access chromedriver via an IP address, he always tries access chromedriver via the localhost. So to put chromedriver to run on localhost, I´m using the following command to relay requests from LOCALHOST:PORT to WINDOWSHOST:PORT.

Command: socat -d -d TCP-LISTEN:9515,reuseaddr,fork TCP:$(cat /etc/resolv.conf | tail -n1 | cut -d " " -f 2):9516

So each request that I did from my wsl2 machine to "localhost:9515" is relayed to "ipaddress:9516". On the windows side, I just need to open the 9516 port on my firewall.

If I can help you with anything else, reach me out! :)

@Uzume
Copy link

Uzume commented Mar 20, 2020

@raelmax It seems you are not using WSL interop sockets at all and instead just using socat to forward Linux guest client (selenium) accesses to a localhost port to a Windows host IP and port (which also requires that the chromedriver server allows connections from IPs other than its own localhost).

I imagine you could have just as easily used netcat or ncat (from nmap package). Thank you, I appreciate the feedback.

@gwd999
Copy link

gwd999 commented Mar 29, 2020

still same issue as of end of March 2020 ... WSL2 [Ubuntu 18.04] on WINDOWS 10 Pro cannot access a defined DISPLAY (no matter how I define it if via localhost:0, or the WSL2 vEthernet adapter IPv4 address) on X-Server (neither Xming nor VcxSrv with and without -ac parameters) running on WINDOWS host system to display any graphic apps (eg xeyes or xclock).

@fquinner
Copy link

fquinner commented Apr 2, 2020

I added some documentation for the issues that I found while trying to get DISPLAY working with WSL 2:

https://github.com/cascadium/wsl-windows-toolbar-launcher#troubleshooting

Ideally though, yes localhost would work and no firewall exceptions would be required (which I would suggest this ticket is primarily for).

@odbayar
Copy link

odbayar commented Apr 5, 2020

WSL2 networking really is a clusterfuck.

@famelis
Copy link

famelis commented Apr 5, 2020

@fquinner I created some scripts, which can be run either when boot or from WSL or from Administrator Powershell.

They launch, in a transparent manner. a windowed KDE, using VcXsrv and the accompanying Xlaunch. It works very well and has no problems with reboots or shutting it down and back again

A working version has been uploaded at:
https://github.com/famelis/wsl2-x11

@shamsalmon
Copy link

@Uzume I´m using Ubuntu 18.04 and I´ve installed socat via apt-get. :)

My use case is as follow:

  • I need to use chromedriver(and chrome) running on Windows(host) and I need to control the chromedriver via selenium running on my Ubuntu(via wsl2).

Since I can´t update my code to access chromedriver via an IP address, he always tries access chromedriver via the localhost. So to put chromedriver to run on localhost, I´m using the following command to relay requests from LOCALHOST:PORT to WINDOWSHOST:PORT.

Command: socat -d -d TCP-LISTEN:9515,reuseaddr,fork TCP:$(cat /etc/resolv.conf | tail -n1 | cut -d " " -f 2):9516

So each request that I did from my wsl2 machine to "localhost:9515" is relayed to "ipaddress:9516". On the windows side, I just need to open the 9516 port on my firewall.

If I can help you with anything else, reach me out! :)

Hey thanks for this solution. What should I change on the code side to get it to use port 9516?

@et304383
Copy link

et304383 commented Jun 1, 2022

I was stuck on this issue until I disabled Windows Firewall for Public Networks. Obviously this isn't the most secure solution, but one must understand that WSL2 networking is based on NAT for outbound (egress) connectivity. As a result, from the standpoint of Windows this is an external machine attempting to connect to its IP on the virtual network that WSL2 uses.

So from Windows perspective, this is an external host trying to connect, and it's not on the private network as that's the one established via your Ethernet or Wi-Fi connection to your router or access point. The WSL2 network is, in essence, a public network so Windows is being cautious by default and not allowing inbound connectivity from WSL2.

To do this properly, in a secure fashion, you need to find the Firewall rule under public networks that is likely disabling your access. For me, it was two entries for "VirtualBox Headless Frontend" that were blocking access for some reason. Once I killed those, I was able to access again.

The networking between WSL2 and Windows is fine; it's likely Windows Firewall that is your issue.

@barbalex
Copy link

barbalex commented Jun 1, 2022

Seing this: Is it not possible for microsoft to solve this firewall issue?

This issue has been open for 2.5 years now and has probably cost hundreds of dev hours.

Please, microsoft, teach your firewall better manners!

@barbalex
Copy link

barbalex commented Jun 1, 2022

I just saw that microsoft has labeled this as feature. This is definitely a horrible bug, not an optional feature!

Seing that this has been downvoted, I will argue why this is a bug, not a feature:

This tool is named WSL2. It is obviously a newer, shinier and better version than it's predecessor, WSL(1). BUT: It does not work, at least not in the way many devs use it.

That is what I call a horrible bug.

@epicmario7133
Copy link

After hours of frustration reverting to wsl1 was the only thing that worked for me:

wsl --set-version Ubuntu 1

it worked thanks :)

@gthvidsten
Copy link

Just encountered this issue myself. $(hostname).local doesn't work from inside dotnet.
I'm surprised that WSL2 doesn't have a hostname common across all environments in the same way the Docker has host.docker.internal.
There should really be a host.wsl2.internal or similar.

@levzlotnik
Copy link

To anyone needing a workaround, run this on the Windows side:

adb -a -P 5037 nodaemon server

and this on WSL2:

adb kill-server
export ADB_SERVER_SOCKET=tcp:192.168.100.5:5037
adb devices

Replace the IP with your windows IP.

Edit: I may have commented on the wrong issue. It was one on the same error but related to Android studio.

I made 2 scripts so I can invoke them whenever I "login" to my development session.

On windows:
Create a ps1 file somewhere in C:/ drive, in my case it's located in C:/Android/make_adb_server.ps1:

# C:/Android/make_adb_server.ps1
taskkill /f /im adb.exe

Start-Process -FilePath adb.exe -ArgumentList "-a -P 5037 nodaemon server" -WindowStyle hidden

timeout 5

adb connect localhost:58526

On WSL2:
Create a shell script that would call the aforementioned file and then define the socket as well. In my case I placed it at ~/start_adb_server.sh:

# ~/start_adb_server.sh
powershell.exe "C:/Android/make_adb_server.ps1"

windows_ip_address=$(grep nameserver /etc/resolv.conf | awk '{print $2}')

export ADB_SERVER_SOCKET="tcp:${windows_ip_address}:5037"

# Verify it works:
adb devices

Then you can setup your adb server directly from WSL2 by calling

source ~/start_adb_server.sh

@layedra
Copy link

layedra commented Jul 16, 2023

@gthvidsten

Just encountered this issue myself. $(hostname).local doesn't work from inside dotnet. I'm surprised that WSL2 doesn't have a hostname common across all environments in the same way the Docker has host.docker.internal. There should really be a host.wsl2.internal or similar.

Apparently Microsoft must've listened to you. I just tried host.docker.internal and it worked! ChatGPT suggested it as well.

@craigloewen-msft
Copy link
Member

Hi folks, we have put out a new update that aims to fix this issue in WSL. In your .wslconfig file you can set experimental.networkingMode=mirrored, as well as some other key settings that should improve your network compatibility! With this you will be able to access Windows servers via localhost. Please try them out and let us know what you think.

More info on this release and the changes can be found here in the blog post.

Please note: You need to be on a Windows Insiders version to use the new networking settings (Any channel of Windows Insiders will do, including release preview). If you see the "These are not supported" messages it means that your current Windows version doesn't have support, and you will need to upgrade. These features will eventually be coming to Windows 11 22H2.

@craigloewen-msft
Copy link
Member

These new networking features are now available on the latest version of Win11 22H2!

Please make sure you're on the latest build to get these features, you can do that by clicking "Check for Updates" in Windows settings. You can check you have the right build by either ensuring you have KB5031354 installed, or run cmd.exe /c ver and ensure that your build number is 22621.2428 or higher (Including the minor build number which is after the . as this was a backport!)

@falkenhawk
Copy link

Are there any chances for the fixes to be backported to Win10? 🙏

@amahpour
Copy link

FYI, latest update, 2.0.14, comes with the fix. Confirmed that it works for me on Win11 22H2.

@kinglite
Copy link

kinglite commented Jan 4, 2024

I installed the version 2.0.14 on my Windows 10. Unfortunatelly the network fix does not work there. So hoping here that it will be available for Windows 10 as well, and soon (Company is not ready yet to update to W11 I'm afraid. Everyone is switching to Macs because it's easier to work when you need linux stuff.)

@tborrman
Copy link

@craigloewen-msft

The .wslconfig edit to set networkingMode=mirrored is not working for me using Microsoft Windows [Version 10.0.22631.3007]
I am trying to port forward Sublime with RemoteSubl using ssh -R 52698:localhost:52698 user@remote-server.
I can see 127.0.0.1:52698 listening on the Windows side through powershell but looking for ports on the WSL Ubuntu terminal with netstat I don't see my port. What does networkingMode=mirrored do? How can I validate its working?

@deadcoder0904
Copy link

@craigloewen-msft @amahpour what is the minimal .wslconfig for using mirrored mode? i'm unable to access localhost:3000 for my next.js app. using wsl2 without docker-desktop. but docker run --rm -ti -p 80:80 nginx works fine & i can see nginx on localhost.

is this config enough?

.wslconfig

[wsl2]
localhostforwarding=true
networkingMode=mirrored
firewall=true

do i have to restart my pc too? or is wsl --shutdown enough?

@amahpour
Copy link

@deadcoder0904 Oddly enough I've got nothing configured except for systemd. What version of Windows and kernel version of WSL are you running?
For windows type winver in the command shell
For WSL go to a command shell and type in wsl --version

Also, I presume your nginx test is Docker via the Windows command shell (not within a bash WSL 2 shell)?

@deadcoder0904
Copy link

winver showed this:

image

wsl --version showed this:

Kernel version: 5.15.133.1-1
WSLg version: 1.0.59
MSRDC version: 1.2.4677
Direct3D version: 1.611.1-81528511
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22631.3155

I presume your nginx test is Docker via the Windows command shell (not within a bash WSL 2 shell)?

i'm using powershell 7. but i'm going into wsl by typing wsl on windows terminal (powershell 7) & then typing that docker run command. i'm using wsl2 without docker desktop bdw.

@amahpour
Copy link

Yeah, you're certainly up to date. So with older versions of WSL 2 (or maybe it was WSL 1) you had to create tunnels or address the IP of the WSL instance (just like you would with a VM). Not sure when the switch happened but Microsoft now defaults WSL to NAT mode. This means that if you've got a a Node app running in WSL (i.e. the example you gave), addressing it via localhost on the Windows side should bring it up.

Some follow up questions:

  • What distro are you using?
  • Did you install it via the Microsoft Store?
  • What happens when you remove all those config options in .wslconfig (and completely restart the computer)?
  • Are you 100% sure there's no firewall policy in your WSL distro?
  • Have you tried address your Node app using the IP of the WSL instance (instead of localhost) just like the old days with VMWare or VirtualBox?

@deadcoder0904
Copy link

deadcoder0904 commented Feb 26, 2024

What distro are you using?

Ubuntu.

Did you install it via the Microsoft Store?

I don't remember. But I think I did wsl --install

What happens when you remove all those config options in .wslconfig (and completely restart the computer)?

Haven't tried it yet.

Are you 100% sure there's no firewall policy in your WSL distro?

I am not sure. I did check & added or removed something in Firewall but don't remember what I did. Is there a way to reset it?

Have you tried address your Node app using the IP of the WSL instance (instead of localhost) just like the old days with VMWare or VirtualBox?

For some reason, my IP never worked. The one I got when I did ipconfig & at the end, there is a WSL IPv4 IP but yeah I couldn't ever get IP working when all answers on the internet say that it will work. It just never did for me.

Bdw, I changed my Dockerfile to use ENV HOSTNAME '0.0.0.0' & it works for now but ENV HOSTNAME localhost doesn't.

What's your suggestion? Do I try removing .wslconfig & restarting? Should I also reset firewall?

@amahpour
Copy link

What version of Ubuntu?

One sure bet way of doing it is install a new distro via the Microsoft Store (you can have many WSL distros at the same time just like your would VMs) and make sure there's no firewall set up. Make sure your .wslconfig is empty as well. Give that a shot and see what happens. I've done this countless times on new machines and, with the latest version of Windows 11 + WSL 2, it's always worked.

@amahpour
Copy link

Regarding localhost versus 0.0.0.0 I can't really comment on how Windows handles all of that. To be honst I've completely forgotten. WSL matured to a point that I develop strictly in it now (versus in Windows, separate Linux machine, or VM)...

@deadcoder0904
Copy link

What version of Ubuntu?

I tried lsb_release -a & got this:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.3 LTS
Release:        22.04
Codename:       jammy

Alright, I'll try it again.

Did you remove localhostforwarding too?

I'm just unsure because I've only recently installed WSL because I wanted to try Docker & Docker doesn't work without WSL but yeah, still some weird errors.

@amahpour
Copy link

amahpour commented Feb 26, 2024

I definitely do not have localhostforwarding set. I highly recommend removing it and/or starting from scratch like I proposed above.

Regarding Docker: that's the beauty of Docker for Desktop. WSL 1 with Docker for Desktop was pretty lackluster but Microsoft did a phenomenal job integrating it with WSL 2. You just need to make sure you enable WSL 2 in the General settings and your distro (in this case Ubuntu 22.04) in Resources > WSL Integration.

FYI, Docker for Desktop + WSL 2 is absolutely the way to go. If you're looking for alternatives (e.g. Docker CE within Linux or Rancher) it's not going to be as seamless.

@deadcoder0904
Copy link

@amahpour so i removed everything in .wslconfig, restarted my pc & it works for now.

the only thing i had to change is use 0.0.0.0 instead of localhost in dockerfile.

for some reason, wsl2 without docker for desktop works much better for me. docker for desktop spins a lot of fans for no reason. it doesn't help i'm using a low-end pc for now. but for low-specs pc, wsl2 without docker desktop is the way.

thanks for the help bdw.

would love to know why localhost as hostname doesn't work? it should because all default templates use localhost. you can try one yourself by cloning a next.js example from https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile (i guess they are using 0.0.0.0 now but i still think its a bug in wsl2)

you can see countless examples here (i'm assuming they are on linux/mac but their windows colleagues will face issues) -> https://sourcegraph.com/search?q=ENV+HOSTNAME+localhost+file%3Adockerfile&patternType=standard&sm=0

@the-moog
Copy link

the-moog commented Mar 13, 2024

I've recently been experimenting with bridging in WSL2. I've tried this many times in the past and had limited and random success.
I've recently worked out why this is and why there is so much said on the subject.

##Simply put
The Win10/11 GUI leaves bits of config inside the hidden network layers, which break later invocations.

##Resolution
However if you use PowerShell, (I know, sadly....), then you can make config that always works!!

Note: I found I had to install some PowerShell helper modules and make sure I'm using an up to date version of PowerShell as it seems Win10 got left behind in that at some point.

##Root cause
What is happening is that, e.g. you have an unused adapter interface on the host machine. When you try and re-configure networking in WSL2, if certain protocol extensions are installed in that adapeter - even if it is disabled and not attached - then WSL2 silently fails to configure the interface(s). If you look under the hood, the extension required on the various interfaces are missing. This explains the random things I've seen. And I found it by issuing the commands in the wrong order.
But in PS I was able to see the obtuse messages that are being kept quiet. e.g. "A protocol on the network adapeter prevented it from binding to the virtual network." or "Ethernet Adapter XYZ is already bound to Microsoft Virtual Switch Protocol" or (and I laughed at this one) "ERROR: Failed whilemodifying virtual switch - Reason: Failed while modifying virtual switch settings" (lol)

I find the old Control Panel Networking view is better than the newer Win10/11 in that you can see things sometimes don't look right... E.g. Things like Up thing being Down, TWO or ZERO copies of "vEthernet (WSL)" I've even seen them with - yep - The same UUID
The properties should look something like this....

I've not got time to document this properly and concisely, but I found the following commands (cut and paste from my notebook) provided the answers... Please, if you are curious enough and just as recless, and go and actually use them to screw your machine up. Don't say I did not warn you and tell you I take no responsibility for what happens.....

** BTW: Some of these won't work without local Administrator rights

Get-NetAdapterBinding | where-object -property Description -like -value '*switch*' | format-table
get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding
get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding | Where-Object -Property ComponentID -eq -value 'vms_pp'
get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding | where-Object  -Property ComponentID -eq -value 'vms_pp'  | Set-NetAdapterBinding -Enabled $False
# OK lets try changing something....
get-NetAdapter | where-object -Property InterfaceDescription -Like -value '*Thun*' | select-object Name | Set-Variable -Value 'Thunderbolt'

# Use Install-Module if the command you need are missing....
Get-Module -All -ListAvailable | Where-Object -Property ModuleType -eq -Value 'Manifest'

Install-Module # (...I did not write the rest of that down)
help module

Get-VMSwitch | Get-VMSwitchExtension | format-table
Get-NetAdapter -IncludeHidden
Get-VMSwitch | select-object -Property Name, Extensions | format-table
Get-NetAdapterBinding
Get-VMSwitchExtension
Get-VMSwitchExtensionSwitchFeature
help Enable-VMSwitchExtension -full
Add-VMSwitchExtensionPortFeature
hvc -v list
hcsdiag list
wsl --system
Get-VM -ComputerName PC | Where-Object {$_.State -eq '*'}
hcsdiag read -uvm 383890C3-1FEE-4E38-B328-B63A87D37A46 \etc\shadow     # Would have been rather jolly if that had worked... :|
Get-NetAdapterAdvancedProperty
Get-help Add-VMSwitchExtensionSwitchFeature -full
# It seems wildcards work
help get-vm*
help vm

With these I was able to see what was happening and clear out any cruft and create the correct switch bound to the correct adaprter with the correct name/settings etc.
I also used the Virtual Switch manager from Hyper-V

I also found that in .wslconfig you can write the following to bind WSL2 to a bridged network called 'Bridge'
But then found you did not even need the actual bridge !!
A VMSwitch alone is enough. I now have a VM (Centos) + WSL + Host all attached to the same LAN network right back over a VPN to the office....

[wsl2]
networkingMode = bridged
vmSwitch = Bridge

Next, see if I can use a bridge and some sort of VLAN or other multiplexing to get more than one adapter and more than one concurrent network.
I think Open vSwitch may be useful...

@jasnei
Copy link

jasnei commented Apr 19, 2024

Oh yes, I have the same issue, but after trying so many configurations from the issue or other issue. still not work.
And I found out it's very easy to connect to windows service from WSL. you just change the IP address from 127.0.0.1 to your windows ip address, which works for me.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8010)

This is a simple example. Then I run on window, normally, we will connect by 127.0.0.1:8010. This works when you were in your windows environment. But from WSL, it's not work. by changing the IP address to your_windows_ip:8010, then you should connect.

~$ curl 192.168.0.7:8010
~$ {"message":"Hello World"}

192.168.0.7 is my windows IP, change to yours.

Vice Verse

If you start your service on WSL, you want to connect from windows, you will need the ip of your wsl

ifconfig

and your could check from PowerShell, well 172.26.43.102 is my WSL IP, you will need to change to yours.

> curl 172.26.43.102:8010

StatusCode        : 200
StatusDescription : OK
Content           : {"message":"Hello World"}
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    Keep-Alive: timeout=4
                    Proxy-Connection: keep-alive
                    Content-Length: 25
                    Content-Type: application/json
                    Date: Fri, 19 Apr 2024 03:14:39 GMT
                    Server: uvicorn
                    ...
Forms             : {}
Headers           : {[Connection, keep-alive], [Keep-Alive, timeout=4], [Proxy-Connection, keep-alive], [Content-Length
                    , 25]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 25

It's working for me here, I hope this will help you too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature wsl2 Issue/feature applies to WSL 2
Projects
None yet
Development

No branches or pull requests