如何从 wsl2 访问 Windows 本地主机?

Mah*_*ian 37 networking tcp gdb windows-subsystem-for-linux wsl2

我的 Windows 11 上安装了 wsl2(ubuntu)。

我已经在 Windows 本地主机上设置了一个 gdb 侦听器服务器,并希望从 wsl2 访问它。但我的 Windows 机器和 wsl 虚拟机似乎使用不同的网络适配器。

>ipconfig

Windows IP Configuration


Ethernet adapter vEthernet (Default Switch):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::1114:bb:d0ad:93f8%18
   IPv4 Address. . . . . . . . . . . : 172.29.192.1
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . :

Ethernet adapter vEthernet (WSL):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::897:849a:5fed:1c6e%52
   IPv4 Address. . . . . . . . . . . : 172.21.128.1
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . :

Run Code Online (Sandbox Code Playgroud)

我的服务器正在积极侦听 8888 端口,并且可以在 Windows 上访问,但不能在 ubuntu 上访问。

我已经从 Windows 防火墙和 ubuntu 防火墙打开了 8888 端口

解决办法是什么?

har*_*ymc 47

localhost不起作用,因为 WSL2 正在使用 Windows 虚拟机平台(Hyper-V 的子集)创建的虚拟网络 (vNIC) 运行。WSL2 内部localhost是 vNIC 的地址。

WSL2 确实在 Windows 主机上设置了一个虚拟路由器,以允许连接到外部世界以及 Windows 主机。您可以通过以下方式查看:

ip route
Run Code Online (Sandbox Code Playgroud)

“默认通过”地址是 Windows 主机使用的地址。

您可以从上面或从 解析它/etc/resolv.conf,但 WSL 还使用 Windows“计算机名称”设置一个方便的 mDNS(.local域),该名称也用作hostnameWSL 实例的名称。

$(hostname)通过连接来访问它.local

尝试:

ping "$(hostname).local"
Run Code Online (Sandbox Code Playgroud)

或者,如果 ICMP 被阻止(在新安装的 Windows 11 上似乎如此),请使用 netcat。默认情况下,它在 WSL Ubuntu 安装中可用,但可能需要安装在 openSUSE 等其他发行版中:

nc -zv "$(hostname).local" <portnumber>
Run Code Online (Sandbox Code Playgroud)

参考: 从 WSL2 内部访问在 Windows 中运行的本地主机? NotTheDr01ds 的回答。

  • 这看起来很像我几天前的 Stack Overflow [答案](/sf/answers/4858494511/):-)。从另一个答案复制/粘贴时,请记住[添加参考/归属](https://meta.stackexchange.com/questions/160071/what-to-do-when-plagiarism-is-discovered)。 (13认同)