从本地网络访问在 WSL(Linux 的 Windows 子系统)上运行的 Web 服务器

新手上路,请多包涵

在将 Ubuntu 安装为 WSL(Linux 的 Windows 子系统)后,我运行了:

 root@teclast:~# python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...

and try to access to this web server from my windows machine http://0.0.0.0:8000 or http://192.168.1.178:8000 but no success, web server available only by the address http://127.0.0.1:8000 or http://localhost:8000 这意味着我无法从网络中的另一台 PC 连接到此 Web 服务器。是否可以从外部访问 WSL?

原文由 Roman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

现有的答案都不适合我,因为 WSL2 在自己的虚拟机中运行并且有自己的网络适配器。您需要某种桥接或端口转发才能使非本地主机请求工作(即来自同一网络上的另一台主机)。

我在 https://github.com/microsoft/WSL/issues/4150 中找到了一个可以解决问题的脚本:

 $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";
}

从提升/管理员 Powershell 会话运行此脚本对我来说是诀窍。这允许访问在同一端口上可从 Windows 主机 IP 访问的端口上运行的 WSL2 服务。

原文由 mlibby 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题