局域网其他主机访问WSL2的方法

1. 为WSL创建外部虚拟交换机

1.1 安装Hyper-V

首先检查“控制面板”->“程序”->“启用或关闭Windows功能”中有没有Hyper-V这一项,如果有就选中它然后重启电脑。
image

我的电脑是windows11家庭版,默认没有Hyper-V,需要手动添加。将以下命令写进记事本:

点击查看代码
pushd "%~dp0"
dir /b %SystemRoot%\servicing\Packages\*Hyper-V*.mum >hyper-v.txt
for /f %%i in ('findstr /i . hyper-v.txt 2^>nul') do dism /online /norestart /add-package:"%SystemRoot%\servicing\Packages\%%i"
del hyper-v.txt
Dism /online /enable-feature /featurename:Microsoft-Hyper-V-All /LimitAccess /ALL
重名为.cmd文件,然后以管理员身份运行。此时因该已经存在Hyper-V了,去启用即可。

1.2 创建虚拟交换机

启动PowerShell,运行 Get-NetAdapter 查找现有网络适配器及其名称:
image

运行以下命令来创建虚拟交换机,将 占位符替换为你自己的值:
New-VMSwitch -Name <switch-name> -NetAdapterName <netadapter-name>
其中就是要创建的虚拟交换机的名称,我的名称叫做“WSLBridge”,是网络适配器的名称,我的是“以太网”

2. 为WSL配置虚拟交换机

首先需要从 Microsoft Store 里面下载最新的 Windows Subsystem for Linux。
然后在当前用户目录 %USERPROFILE% 下面创建一个配置文件 .wslconfig,按照如下配置方法设置网络,例如:

点击查看代码
[wsl2]
networkingMode=bridged
vmSwitch=WSLBridge
ipv4=true
ipv6=true
重启WSL2。

参考

  1. https://www.jianshu.com/p/96aa6eeacb56
  2. https://learn.microsoft.com/zh-cn/windows-server/virtualization/hyper-v/get-started/create-a-virtual-switch-for-hyper-v-virtual-machines?tabs=powershell
  3. https://zhuanlan.zhihu.com/p/593263088
posted @ 2023-03-18 15:45  luckilzy  阅读(766)  评论(0编辑  收藏  举报