WSL2中自动配置Windows IP地址

在内测版的WSL2中,WSL本身运行在虚拟机中,因此不能使用本地回环(localhost, 127.0.0.1),导致无法直接使用代理服务器,又由于每次网络变化生成的ip地址都不同,因此整个配置过程极为复杂。

经过测试,可以采用一下办法,通过/etc/hosts来将一个特定的域名重定向到主机

具体shell文件如下:

#!/bin/sh
export HOSTIP=$(cat /etc/resolv.conf | grep 'nameserver' | cut -f 2 -d ' ')
export CLIENTIP=$(ip addr show eth0 | grep 'inet ' | cut -f 6 -d ' ' | cut -f 1 -d '/')
echo $HOSTIP
echo $CLIENTIP
echo <Your password> | sudo -S sed -i "/host/c $HOSTIP\thost" /etc/hosts 

2020 年 5 月 8 日更新:增加了对 proxychains 的设置,以及同步修改 Windows hosts 文件,以及 Ex mode 从管道读入修改失败,换成了另一种方式
2020 年 6 月 15 日更新:需要 Windows 设置可写入,右键 host 文件,属性-安全-高级,把 Windows 登录用户给予“完全控制”权限即可

#!/bin/sh
export WINIP=$(cat /etc/resolv.conf | grep 'nameserver' | cut -f 2 -d ' ') 
export WSLIP=$(ip addr show eth0 | grep 'inet ' | cut -f 6 -d ' ' | cut -f 1 -d '/')
echo WINIP $WINIP
echo WSLIP $WSLIP

echo <Your password> | sudo -S sed -i "/winip/c $WINIP\twinip" /etc/hosts
echo <Your password> | sudo -S sed -i "/socks5/c socks5\t$WINIP 1080" /etc/proxychains.conf

vim "+:%s/^.*winip/$WINIP\t\twinip/g" "+:%s/^.*wslip/$WSLIP\t\twslip/g" '+:wq' -E /mnt/c/Windows/System32/drivers/etc/hosts  

将其放置在环境变量里,并设置可执行权限(如果文件名是net则执行chmod a+x net)。每次网络变化后执行net即可
在VSCode等需要配置代理的地方,直接使用http://winip:1081即可正常使用代理

如果需要在 Windows 中通过127.0.0.1localhost访问 WSL2 服务,则可以在用户目录下建立.wslconfig,并写入

[wsl2]
localhostForwarding=true