WSL2に立てたサーバーに同ネットワークにある別端末からアクセスする
WSL上で開発をしていて立てたサーバーに別端末からアクセスする方法です。
Macでは何もせずにアクセスできたのですが、WSLの場合、Windows側にポートフォワーディングを設定する必要があります。
WSLのIPを調べる
ifconfig
で確認
172.21.171.162
の部分
$ ifconfig eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.21.171.162 netmask 255.255.240.0 broadcast 172.21.175.255 inet6 fe80::215:5dff:fe53:6719 prefixlen 64 scopeid 0x20<link> ether 00:15:5d:53:67:19 txqueuelen 1000 (イーサネット) RX packets 25699 bytes 10913242 (10.9 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 4954 bytes 2993879 (2.9 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (ローカルループバック) RX packets 109531 bytes 128195327 (128.1 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 109531 bytes 128195327 (128.1 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
PowerShellでポートフォワーディングを設定
※管理者として実行してください
$ netsh interface portproxy add v4tov4 listenport=3000 connectaddress=[先程調べたIP]` $ netsh interface portproxy add v4tov6 listenport=3000 connectaddress=::1
※ 2022/01/05 IP周りの設定が変わったのかアクセスできなくなっていたので v4tov6 周りの設定を追加 matsudamper.hatenablog.com
設定されているポートフォワーディングは
netsh interface portproxy show v4tov4
netsh interface portproxy show v4tov6
で確認可能
PS C:\WINDOWS\system32> netsh interface portproxy add v4tov4 listenport=3000 connectaddress=172.21.171.162 PS C:\WINDOWS\system32> netsh interface portproxy add v4tov6 listenport=3000 connectaddress=::1 PS C:\WINDOWS\system32> netsh interface portproxy show v4tov4 ipv4 をリッスンする: ipv4 に接続する: Address Port Address Port --------------- ---------- --------------- ---------- * 3000 172.21.171.162 3000