Windows 11 WSL2 配置静态 IP 的实现方案
基于评论 https://github.com/microsoft/WSL/issues/4210#issuecomment-648570493 的思路,我给出一个实现静态IP效果的变通方法。
第一步:在 WSL2 Linux 环境中创建脚本文件
vim /home/likfees/Shell/static-ip.sh
#!/bin/bash
/mnt/c/WINDOWS/system32/netsh.exe interface ip show addresses "vEthernet (WSL)" | /mnt/c/WINDOWS/system32/findstr.exe /C:"172.18.16.1" > /dev/null
if [ $? == 1 ]; then
/mnt/c/WINDOWS/system32/netsh.exe interface ip add address "vEthernet (WSL)" address=172.18.16.1/24
fi
ip addr show eth0 | grep -s "172.18.16.100/24" > /dev/null
if [ $? == 1 ]; then
ip addr add 172.18.16.100/24 broadcast 172.18.16.255 dev eth0 label eth0:1
fi
注意:该脚本旨在为 Windows 端的 "vEthernet (WSL)" 接口分配 IPv4 地址 172.18.16.1,并为 Linux 端的 eth0 接口添加 IPv4 地址 172.18.16.1。使用前请根据实际需求调整网络接口名称及 IP 地址参数。
第二步:在 WSL2 启动时自动执行该脚本
vim /etc/profile 中添加以下内容
sudo /home/likfees/Shell/static-ip.sh
如果 eth0 重新获取了 IP 地址,则需要手动运行 static-ip.sh 脚本来重新应用静态配置。
第三步:解决 Win11 能 ping 通 WSL2,但 WSL2 无法 ping 通 Win11 的问题。经分析,这主要归因于 Win11 的防火墙设置。请在 Win11 中以管理员身份运行 PowerShell 或 CMD,并执行以下命令:
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow
第四步:使用静态 IP
Windows 端静态 IP 设置为 172.18.16.1;WSL Linux 端静态 IP 设置为 172.18.16.100。
附:Win11 WSL2 固定 IP 完整方案
背景说明
在 Win11 上通过 WSL2 安装了 Ubuntu,希望其他电脑能通过 SSH 登录 Linux。但由于每次电脑重启后 WSL 的 IP 都会发生变化,因此寻找了一个脚本以实现 WSL IP 的固定。
脚本实现
@echo off
setlocal enabledelayedexpansion
::先停掉可能在跑的wsl实例
wsl --shutdown ubuntu
if !errorlevel! equ 0 (
::检查WSL有没有我需要的IP
wsl -u root ip addr | findstr "192.168.3.100" > nul
if !errorlevel! equ 0 (
echo wsl ip has set
) else (
::IP不存在则绑定IP
wsl -u root ip addr add 192.168.3.100/24 broadcast 192.168.3.255 dev eth0 label eth0:1
echo set wsl ip success: 192.168.3.100
)
::检查宿主机有没有我需要的IP
ipconfig | findstr "192.168.3.200" > nul
if !errorlevel! equ 0 (
echo windows ip has set
) else (
::IP不存在则绑定IP
netsh interface ip add address "vEthernet (WSL)" 192.168.3.200 255.255.255.0
echo set windows ip success: 192.168.3.200
)
)
::为主机设置SSH转发端口
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=22 connectaddress=192.168.3.100 connectport=22
pause
至此,关于 Windows 11 WSL2 添加静态 IP 的文章介绍完毕。如需了解更多相关内容,请搜索本站历史文章或继续浏览下方推荐内容,感谢支持!