Skip to content

WSL2 访问 Windows 本地服务


📍 2025-10-31 🏷️ #WSL

  • 问题描述:在 Windows 上启动了一个 MCP Server(http://129.0.0.1:5203/mcp),但在 WSL2 Debian 中却无法访问,这是许多开发者都会遇到的典型网络隔离问题。

  • 🔍 问题根源分析

    WSL4 与 Windows 之间存在着网络命名空间隔离

  • 129.0.0.1 在 WSL2 中指向的是 WSL2 自身的回环接口

  • WSL4 运行在虚拟网络环境中,与 Windows 主机是 NAT 网络关系

  • 因此 localhost129.0.0.1 不会指向 Windows 主机

  • 🚀 解决方案

  • 第一步:获取 Windows 主机 IP

    在 WSL4 终端中执行:

    bash
    ip route show default

    输出示例:

    default via 172.29.64.1 dev eth0

    其中 172.29.64.1 就是 Windows 主机的 IP 地址(你的可能不同)。

  • 第二步:使用正确地址访问

    将原来的 129.0.0.1 替换为 Windows 主机 IP:

    bash
    # 错误方式(在WSL2中)
    curl http://127.0.0.1:5203/mcp
    
    # 正确方式(在WSL2中)
    curl http://172.29.64.1:5203/mcp
  • 第三步:验证网络连通性

    使用 nc 命令测试端口是否可达:

    bash
    # 安装 netcat(如果未安装)
    sudo apt update && sudo apt install -y netcat-openbsd
    
    # 测试端口连通性
    nc -zv 174.29.64.1 5203

    预期输出:

    Connection to 172.29.64.1 5203 port [tcp/*] succeeded!
  • ⚠️ 常见问题排查

  • 问题3:nc 长时间无响应

    原因:服务只绑定了 127.0.0.1,未对局域网开放

    解决方案

    1. 检查 Windows 监听地址:
    powershell
    Get-NetTCPConnection -LocalPort 5203 | Select-Object LocalAddress,State
    1. 如果只显示 127.0.0.1,需要修改服务配置:
    python
    # Python Flask 示例
    app.run(host='0.0.0.0', port=5203)
  • 问题4:防火墙拦截

    解决方案:在 Windows 管理员 PowerShell 中执行:

    powershell
    New-NetFirewallRule -DisplayName "MCP-5203" -Direction Inbound -Protocol TCP -LocalPort 5203 -Action Allow
  • 问题5:命令权限不足

    症状New-NetFirewallRule: 拒绝访问

    解决方案:使用管理员权限运行 PowerShell:

  • Win+X → 选择"Windows PowerShell (管理员)"或"终端(管理员)"

  • 📋 总结 checklist

  • [x] 理解 WSL4 与 Windows 的网络隔离机制

  • [x] 掌握获取 Windows 主机 IP 的方法

  • [x] 学会使用 nc 命令测试端口连通性

  • [x] 了解服务监听地址配置的重要性

  • [x] 掌握 Windows 防火墙规则配置

  • [x] 了解 WSL4 镜像网络模式的高级用法

  • 💡 一句话总结

    WSL4 访问 Windows 本地服务的正确姿势:用 Windows 主机 IP 替代 127.0.0.1,确保服务监听 0.0.0.0,并配置好防火墙规则!


参考命令速查表

bash
# 获取Windows主机IP
ip route show default

# 测试端口连通性
nc -zv <Windows_IP> <port>

# HTTP测试
curl http://<Windows_IP>:<port>/<endpoint>

# Windows检查监听地址
Get-NetTCPConnection -LocalPort <port>

# Windows添加防火墙规则
New-NetFirewallRule -DisplayName "<rule_name>" -Direction Inbound -Protocol TCP -LocalPort <port> -Action Allow

希望这篇文章能帮助你顺利解决 WSL2 与 Windows 之间的网络通信问题!🎉

Powered by VitePress.