无法从Windows主机连接到WSL2上的本地服务器

3
我有一个Python3项目,在WSL2/Ubuntu 20上使用waitress进行本地托管。我从VSCode远程启动服务器,但无法使用http://127.0.0.1:5998或http://localhost:5998地址从Windows浏览器连接,出现“无法连接”的错误。我无法找到问题所在,感激任何帮助。
Python服务器:
@app.route('/')
def index():
    return 'Success'
...
if __name__ == '__main__':
    from waitress import serve
    process_count = multiprocessing.cpu_count()
    serve(app, host="0.0.0.0", port=5998, threads=process_count)

我看到它正在WSL上运行:

> sudo lsof -i -P -n | grep LISTEN
python3 1263 xxx    8u  IPv4  39138      0t0  TCP *:5998 (LISTEN)

我也尝试将127.0.0.1作为serve()的ip,而不是0.0.0.0,但没有帮助。

我的Windows防火墙中有一个规则:

> Get-NetFirewallRule -DisplayName WSL

Name                  : {9c5c5f2b-a9c7-42b7-82ac-f0c2b1819103}
DisplayName           : WSL
Description           :
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Any
Platform              : {}
Direction             : Inbound
Action                : Allow
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
Owner                 :
PrimaryStatus         : OK
Status                : The rule was parsed successfully from the store. (65536)
EnforcementStatus     : NotApplicable
PolicyStoreSource     : PersistentStore
PolicyStoreSourceType : Local

我使用netstat -o检查了Windows上正在使用的端口,似乎没有任何东西在使用5998端口。

1个回答

19

我通过在Windows上添加端口转发来解决了这个问题。

在WSL上运行以下命令:

ifconfig

eth0入口的inet IP是您的WSL IP。

在Windows上运行此命令:

netsh interface portproxy add v4tov4 listenport=<port> listenaddress=0.0.0.0 connectport=<port> connectaddress=<your WSL IP>

此后,我可以在Windows浏览器中使用 localhost:<port>127.0.0.1:<port> 或者 <WSL IP>:<port> 进行连接。

您可以使用命令 netsh interface portproxy show all 列出当前的端口代理。

您可能需要为Windows上的端口添加防火墙规则。请参考此链接

更多信息请参见:https://github.com/microsoft/WSL/issues/4150#issuecomment-927091364


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接