通过局域网访问Windows10的WSL2的网络服务

1、应用场景

Windows10的WSL2:运行服务端程序,监听127.0.0.1:5000;
Windows10:连接路由器;
手机:和Windows10连上同一个路由器,在同一局域网;
目的:使用手机访问 Windows10 WSL2 的服务。

2、网络分析

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

    以太网适配器 vEthernet (WSL (Hyper-V firewall)):
    
       连接特定的 DNS 后缀 . . . . . . . :
       本地链接 IPv6 地址. . . . . . . . : fe80::4d04:80f0:6738:6b4a%38
       IPv4 地址 . . . . . . . . . . . . : 172.23.176.1
       子网掩码  . . . . . . . . . . . . : 255.255.240.0
       默认网关. . . . . . . . . . . . . :
    

    WSL2:

    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet 172.23.183.165  netmask 255.255.240.0  broadcast 172.23.191.255
            inet6 fe80::215:5dff:fe91:93c8  prefixlen 64  scopeid 0x20<link>
            ether 00:15:5d:91:93:c8  txqueuelen 1000  (Ethernet)
            RX packets 55907  bytes 79137186 (79.1 MB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 18812  bytes 2828512 (2.8 MB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    

    注意:在 Windows 10 主机上可以通过localhost:5000访问 WSL2 的服务,等同于172.23.183.165:5000, 但注意127.0.0.1:5000不可以;

  • 2.2、Windows 10 主机与手机所处的同一个子网:
    Windows 10:

    无线局域网适配器 本地连接* 10:
    IPv4 地址 . . . . . . . . . . . . : 192.168.8.110
    子网掩码  . . . . . . . . . . . . : 255.255.255.0
    

    手机:

    IP 地址:192.168.8.218
    网络掩码:255.255.255.0
    网关:192.168.8.1
    

3、原理及实现方法

在 Windows 10 主机上配置端口转发,将手机端向192.168.8.110:5000的访问请求转发至 172.23.183.165:5000

  • 3.1、使用管理员打开 Powershell,配置端口转发:
    netsh interface portproxy add v4tov4 listenport=5000 connectaddress=172.23.183.165 connectport=5000
    
    配置防火墙添加允许入站规则:
    New-NetFirewallRule -DisplayName "Allow Inbound TCP Port 5000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5000
    
  • 3.2、补充
    删除配置的命令:
    # 查看已配置的端口转发
    netsh interface portproxy show v4tov4
    
    # 删除对应的端口转发
    netsh interface portproxy delete v4tov4 listenport=5000
    
    # 删除防火墙配置
    Remove-NetFirewallRule -DisplayName "Allow Inbound TCP Port 5000"
    
  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值