尝试绑定 IP 结果一重启就回到解放前,只能是想一个其它办法来绕过,毕竟 IP 可变,但是 hostname 可以固定不变。
每次在 wsl 启动后把 ip 更新到 windows 的 etc/hosts 文件里面不就行了? 就按这个思路来。
# 拿到 wsl 的 ip 地址 $ipLine = wsl --exec ip -a a | findStr inet | findStr eth0 $wslIP = $ipLine.trim().split(" |/")[1] echo "WSL new ip is: " $wslIP # 写入 etc\hosts 文件中 $hostsPath = "$env:windir\System32\drivers\etc\hosts" if($wslIP) { $newHosts = Get-Content $hostsPath | Foreach {if ($_ -match '^\s*([^#].*?\d{1,3}.*?wsl.*)') { $wslIP + " wsl"} else {$_}} echo $newHosts $newHosts | Out-File $hostsPath -enc ascii }
保存到 test.ps1
文件中运行即可。
开心。
此脚本仅提供一个思路,如果能运行是最让人开心的,如果不能需要调整一下脚本中具体的关键词,如 eth0, wsl 等等
![]() | 1 vone 2021-01-27 17:12:52 +08:00 通过访问 localhost 不是会自动转发吗 |
![]() | 2 szq8014 OP @vone 哦,艹,原来 localhost 还给转发了。。哈哈哈哈哈哈,解决了一个不存在的问题,一直只使用 IP 的。。原来 WSL 还有魔法 |
![]() | 3 CuriousBull 2021-01-27 17:29:50 +08:00 在别的地方看到设置 wsl2 图形界面设置,有使用以下语句 `export DISPLAY=$(ip route | awk '{print $3; exit}'):0` 仿照类似的句式,配合 clash,同样可以设置代理端口设置,譬如 `export https_proxy=$(ip route | awk '{print $3; exit}'):7890` |
![]() | 4 szq8014 OP @CuriousBull 哈哈,你这个是反过来用 |
5 cymanbu 2021-01-28 17:59:04 +08:00 我是通过主动设置 ip 的方式来实现的固定 ip 地址。https://blog.csdn.net/manbu_cy/article/details/108476859 |