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"