====== 設定讓外部主機可連上 WSL 內的服務(Port Forwarding) ======
* 雖然 wsl 內所啟動的服務 Exp. web 可以在本機使用 localhost 連上, 但無法讓其他區網的電腦聯上使用, 但可在本機上設定 Port Forwarding 來解決這問題
* 以下是範例的環境資訊
* 本機的 IP :
- 無線區域網路介面卡 Wi-Fi:
連線特定 DNS 尾碼 . . . . . . . . : iii.org.tw
IPv4 位址 . . . . . . . . . . . . : 140.92.168.39
子網路遮罩 . . . . . . . . . . . .: 255.255.254.0
預設閘道 . . . . . . . . . . . . .: 140.92.168.1
- 乙太網路卡 vEthernet (WSL):
連線特定 DNS 尾碼 . . . . . . . . :
連結-本機 IPv6 位址 . . . . . . . : fe80::3b0a:1bfd:5727:8f91%88
IPv4 位址 . . . . . . . . . . . . : 172.29.240.1
子網路遮罩 . . . . . . . . . . . .: 255.255.240.0
預設閘道 . . . . . . . . . . . . .:
* WSL 內 Ubuntu 22.04 的 IP :
- eth0: flags=4163 mtu 1500
inet 172.29.251.104 netmask 255.255.240.0 broadcast 172.29.255.255
inet6 fe80::215:5dff:fe6b:64b prefixlen 64 scopeid 0x20
ether 00:15:5d:6b:06:4b txqueuelen 1000 (Ethernet)
RX packets 323 bytes 515846 (515.8 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 296 bytes 26606 (26.6 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
===== 設定程序 =====
* 目標要設定只要 Wifi 區網其他電腦連入本機的 Wifi 網卡 port 80, 443 就會轉成連入 vEthernet(WSL) 的 port 80, 443
* 開啟 Powershell 設定 netsh interface portproxy add v4tov4 listenport=[PORT] listenaddress=0.0.0.0 connectport=[PORT] connectaddress=[WSL_IP]
netsh interface portproxy add v4tov4 listenport=80 listenaddress=0.0.0.0 connectport=80 connectaddress=172.29.251.104
netsh interface portproxy add v4tov4 listenport=443 listenaddress=0.0.0.0 connectport=443 connectaddress=172.29.251.104
* 確認設定是否成功 netsh interface portproxy show v4tov4 \\ {{:tech:2024-01-12_130445.png|}}
* 需要開啟 Windows 防火牆 New-NetFirewallRule -DisplayName "WSL2 Port Bridge" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80,443 \\ {{:tech:2024-01-12_130601.png|}}
===== 參考網址 =====
* https://jwstanly.com/blog/article/Port+Forwarding+WSL+2+to+Your+LAN/
{{tag>wsl windows-linux}}