python-3.x - 无法从 Windows 主机连接到 WSL2 上的本地服务器

标签 python-3.x windows visual-studio-code wsl-2 waitress

我有一个 Python3 项目使用 waitress 在 WSL2/Ubuntu 20 上的本地主机上服务。我从 VSCode 远程启动服务器,但我无法使用地址 http://127.0.0.1:5998 从 Windows 上的浏览​​器连接到它或 http://localhost:5998,无法连接错误。我找不到它有什么问题,感谢任何帮助。

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。

最佳答案

我已经通过在 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>

在此之后我可以使用 localhost:<port> 进行连接或 127.0.0.1:<port><WSL IP>:<port>从 Windows 上的浏览​​器。

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

您可能需要 add a firewall rule适用于您在 Windows 上的端口。

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

关于python-3.x - 无法从 Windows 主机连接到 WSL2 上的本地服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70566305/

相关文章:

python - pandas 数据帧按列的最小与最大差异

windows - 在 Windows 服务中,停止和暂停有什么区别?

c - 读取特定格式的字符串

windows - Windows 上的 Git - SSL 证书错误

git - Visual Studio Code : automatic commit git

algorithm - 使用Python和DFS算法的递归深度问题

javascript - 使用 javascript (jquery) 在 django 中重定向表单提交

visual-studio-code - 您可以在 VS Code 中按路径创建文件或文件夹吗?

json - Pandas:将 JSON 转换为 Pandas Dataframe

python - 为什么 VSCODE 不接受 Python import 语句,而 Pycharm 可以?