Window11 WSL2 添加静态 IP
基于评论 https://github.com/microsoft/WSL/issues/4210#issuecomment-648570493 的思路,我给出一个实现静态 IP 效果的变通方法。
在 WSL2 Linux 中创建一个脚本文件
vim /home/likfees/Shell/static-ip.sh
1
2
3
4
5
6
7
8
9
10
11!/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
添加以下内容1
sudo /home/likfees/Shell/static-ip.sh
当然如果让 eth0 重新获取了 IP,那么需要手动运行
static-ip.sh
。
win11 能够 ping 通 wsl2,但是 wsl2 无法 ping 通 win11, 经分析主要是 win11 防火墙的原因.
在 win11 中 执行如下命令 (管理员运行 powershell 或 cmd):1
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