WSL2 局域网访问以及hosts注意事项

说明:WSL2用的是NAT方式,虚拟机有内部的ip,所以访问虚拟机可用代理访问方法

要点:

- 根据微软文档,powershell 下做端口转发代理:

netsh interface portproxy add v4tov4 listenport=80 listenaddress=0.0.0.0 connectport=80 connectaddress=172.25.250.32
netsh interface portproxy show all

其中172.25.250.32是wsl2的内部ip,可通过wsl2中ifconfig获取

- 因系统重启后,内部ip都会改变,每次都做映射的话极其不便,有人做了powershell脚本,方便使用:

下述代码保存到 C:\Windows\System32\wsl2-network.ps1, 以管理员身份启动powershell,执行即可映射代理

$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';

if( $found ){
  $remoteport = $matches[0];
} else{
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

#[Ports]

#All the ports you want to forward separated by coma
$ports=@(80,443,10000,3000,5000);


#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";


#Remove Firewall Exception Rules
#iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";

#adding Exception Rules for inbound and outbound Rules
#iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
#iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";

for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
  iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}

- hosts, 做本机domain时,需同时兼容 ipv4与ipv6访问(微信小程序,chrome对ipv6即 ::1不敏感)

::1       api-fe-ia-te001.local.com
127.0.0.1 api-fe-ia-te001.local.com

参考:

- Comparing WSL 1 and WSL 2 | Microsoft Docs

- ruby on rails - Connecting to WSL2 server via local network - Stack Overflow

你可能感兴趣的:(技术笔记,windows)