Loading

Window11 WSL2 添加静态IP

基于评论 https://github.com/microsoft/WSL/issues/4210#issuecomment-648570493 的思路,我给出一个实现静态IP效果的变通方法。

  1. 在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地址。

  2. 在 WSL2 启动的时候执行该脚本

    vim /etc/profile 添加以下内容

    sudo /home/likfees/Shell/static-ip.sh
    

    当然如果让 eth0 重新获取了 IP,那么需要手动运行 static-ip.sh

  3. win11 能够 ping 通 wsl2,但是 wsl2 无法 ping 通 win11, 经分析主要是 win11 防火墙的原因.
    在 win11 中 执行如下命令(管理员运行 powershell 或 cmd ):

    New-NetFirewallRule -DisplayName "WSL" -Direction Inbound  -InterfaceAlias "vEthernet (WSL)"  -Action Allow
    
  4. 使用静态IP

​ Windows 端静态IP 172.18.16.1
​ WSL Linux 端静态IP 172.18.16.100

posted @ 2022-10-03 12:23  白日醒梦  阅读(1291)  评论(0编辑  收藏  举报