1. 确保 WSL 版本为 WSL 2
wsl -l -v
如果是 WSL 2,继续进行以下步骤。如果是 WSL 1,可以考虑升级到 WSL 2,或者根据需求使用 WSL 1。
2. 修改 wsl.conf 文件
编辑 WSL 中的 /etc/wsl.conf 文件,添加以下内容:
[network]
generateResolvConf = false
这个配置将阻止 WSL 自动生成 resolv.conf 文件。
3 用户根目录(win+r 输入 %USERPROFILE% 运行进入用户根目录) 新建个名为.wslconfig的文件
[experimental]
networkingMode=mirrored
dnsTunneling=true
firewall=true
autoProxy=true
hostAddressLoopback=true
3. 创建静态 IP
在 Windows 中,使用管理员权限 打开 PowerShell,并运行以下命令,将 WSL 的虚拟网络接口设置为静态 IP:
netsh interface ip set address "vEthernet (WSL)" static <Desired_IP_Address> <Subnet_Mask> <Gateway>
<Desired_IP_Address> 为宿主的 IP 地址 <Subnet_Mask> 为宿主子网掩码 为宿主网关地址
4. 设置 WSL 的 resolv.conf 文件
返回 WSL 中,编辑 /etc/resolv.conf 文件,手动设置 DNS 服务器。你可以设置为宿主机的 IP:
nameserver <Desired_IP_Address>
为了wsl 中能访问外网 需在/etc/resolv.conf 文件末尾添加 DNS 服务器
nameserver 8.8.8.8
nameserver 8.8.4.4
4. 重启 WSL
wsl --shutdown
5. 验证设置是否成功
ip a
ping www.baidu.com