将 Windows 端口转发到 WSL2

将 Windows 端口转发到 WSL2

我有一个用例,我在 Windows 和 WSL2 上进行开发,并且需要使 .NET 应用程序能够在 Windows 上的端口 44301 上提供服务,并且可以从 localhost:44301 上的 WSL2 (Ubuntu) 中进行访问。

我知道 Windows 主机有一个 IP,可以从 WSL2 中访问(可以使用 发现grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'),但这不是我想要实现的目标。我想做的是将 Windows 上的 44301 端口转发到 WSL2 上的 localhost:44301

答案1

我对 WSL2 不太了解,但在真正的 Linux 上你可能会这样做:

#!/bin/sh
SERVERIP=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}')

# Turn on the IPv4 packet forwarding master switch
sysctl net.ipv4.ip_forward=1

# Change the destination of TCP packets arriving to loopback interface's
# port 44301 to the same port on the actual Windows server
iptables -t nat -A PREROUTING -i lo -p tcp --dport 44301 -j DNAT --to-destination $SERVERIP

# Allow the forwarding of any existing forwarded connections
# (to ensure replies from the Windows server are also allowed)
iptables -t filter -A FORWARD -m conntrack --ctstate ESTABLISHED -j ACCEPT

# Allow the forwarding of connections arriving to loopback TCP port 44301
iptables -t filter -A FORWARD -p tcp -i lo --dport 44301 -j ACCEPT

相关内容