通过局域网访问 Windows 10 WSL 2 的网络服务

应用场景

  1. Windows10 WSL2:运行服务端程序,监听 127.0.0.1:8080
  2. Windows10:开启网络热点
  3. 手机:连接 Windows10 网络热点
  4. 目的:使用手机访问 Windows10 WSL2 的服务

网络分析

  1. Windows 10 主机与 WSL2 所处的同一个子网:
  • Windows 10

    以太网适配器 vEthernet (WSL):
       IPv4 地址 . . . . . . . . . . . . : 172.24.64.1
       子网掩码  . . . . . . . . . . . . : 255.255.240.0
    
  • WSL2

    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet 172.24.65.38  netmask 255.255.240.0  broadcast 172.24.79.255
    
    default via 172.24.64.1 dev eth0
    172.24.64.0/20 dev eth0 proto kernel scope link src 172.24.65.38
    
  • 注意:在 Windows 10 主机上可以通过 localhost:8080 访问 WSL2 的服务,等同于 172.24.64.38:8080 但注意 127.0.0.1:8080 不可以;

  1. Windows 10 主机与手机所处的同一个子网:
  • Windows 10
    无线局域网适配器 本地连接* 10:
       IPv4 地址 . . . . . . . . . . . . : 192.168.137.1
       子网掩码  . . . . . . . . . . . . : 255.255.255.0
    
  • 手机
    IP 地址:192.168.137.163
    网络掩码:255.255.255.0
    网关:192.168.137.1
    

原理及实现方法

在 Windows 10 主机上配置端口转发,将手机端向 192.168.137.1:8080 的访问请求转发至 172.24.65.38:8080

  • 使用管理员打开 Powershell
  • 配置端口转发:
    C:\Users> netsh interface portproxy add v4tov4 listenport=8080 connectaddress=172.24.65.38 connectport=8080
    
  • 配置防火墙添加允许入站规则:
    C:\Users> New-NetFirewallRule -DisplayName "Allow Inbound TCP Port 8080" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8080
    

补充

  • 删除配置的命令
    C:\Users> netsh interface portproxy show v4tov4
    C:\Users> netsh interface portproxy delete v4tov4 listenport=8080
    C:\Users> Remove-NetFirewallRule -DisplayName "Allow Inbound TCP Port 8080"
    
  • WSL2 的 IP 地址可能会变,所以需要修改端口转发规则,或者根据参考链接通过函数自动化实现

参考

Windows 10 WSL 2 网络配置
如何在局域网的其他主机上中访问本机的WSL2

posted @ 2022-06-02 11:15  tofengz  阅读(4738)  评论(0编辑  收藏  举报