在使用Windows的wsl时,经常需要Linux子系统和Windows宿主机之间通信。但wsl默认情况下,Linux子系统和Windows vEthernet虚拟适配器的IP每次启动后都不一样。给很多应用带来不便。在百度上很多解决方法,经过之次尝试,认为下面的方法简单有效。
我解决此问题时的系统环境:
宿主机:Windows 10 专业版 22H2 操作系统内部版本:19045.2311
子系统:Ubuntu 22.04.1 LTS Linux version 5.10.16.3-microsoft-standard-WSL2 (oe-user@oe-host)
1.设置Windows vEthernet为固定IP
2. 确认Linux子系统的名称
打开Windows命令提示符查看Linux子系统名称
C:\Users\zhangcheng>wsl -l
适用于 Linux 的 Windows 子系统分发版:
Ubuntu (默认) #记住这个名称,脚本里要用
docker-desktop-data
docker-desktop
3. 编写一个bat脚本并执行
打开记事本,把下面这段代码按照自己的运行环境配置。
@echo on
REM 先关闭虚拟子系统
wsl --shutdown
REM 以下的Ubuntu为第2步查到的Linux子系统名称
REM IP地址根据自己的需要配置
wsl -d Ubuntu -u root ip addr del $(ip addr show eth0 ^| grep 'inet\b' ^| awk '{print $2}' ^| head -n 1) dev eth0
wsl -d Ubuntu -u root ip addr add 172.30.16.2/24 broadcast 172.30.16.255 dev eth0
wsl -d Ubuntu -u root ip route add 0.0.0.0/0 via 172.30.16.1 dev eth0
powershell -c "Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 172.30.16.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 172.30.16.0/24;"
REM 启动对应Linux系统
wt -p Ubuntu
保存成.bat文件后右击选择“以管理员身份运行”。再次打开Ubuntu就是脚本里指定的IP了。文章来源:https://www.toymoban.com/news/detail-408010.html
Done.文章来源地址https://www.toymoban.com/news/detail-408010.html
到了这里,关于Windows中wsl2为虚拟Linux子系统设置固定IP的方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!