把VPS的公网IP通过VPN隧道转发给其他设备
1

当我们使用frp之类的内网穿透工具时,虽然能够让内网服务获得公网访问能力,但存在一个关键问题:不是所有应用都能通过Proxy protocol获取真实的客户端IP地址。本文通过建立VPS与家庭网络之间的VPN隧道,将VPS的公网IP直接"借给"家庭网络中的设备使用,实现真正的IP地址透传。

网络拓扑

Internet  ←→  VPS(公有云)  ←→  WireGuard  ←→  家庭路由器  ←→  内网设备
                 ↑                               ↑             ↑
      网卡IP: 192.168.0.79            内网IP: 192.168.100.1   目标设备: 192.168.100.10
       WG IP: 100.65.0.1               WG IP: 100.65.0.2

VPS端

# 开启IP转发
echo 'net.ipv4.ip_forward=1' | tee -a /etc/sysctl.conf
sysctl -p /etc/sysctl.conf
# 让WireGuard网段的流量能正常返回
iptables -t nat -A POSTROUTING -s 100.65.0.0/24 -j MASQUERADE
# 转发到客户端
iptables -t nat -A PREROUTING -d 192.168.0.79 -p tcp -j DNAT --to-destination 100.65.0.2
# 先排除WireGuard端口,再做DNAT
iptables -t nat -A PREROUTING -d 192.168.0.79 -p udp --dport 12321 -j ACCEPT
iptables -t nat -A PREROUTING -d 192.168.0.79 -p udp ! --dport 12321 -j DNAT --to-destination 100.65.0.2

本地路由器

# 开启IP转发
echo 'net.ipv4.ip_forward=1' | tee -a /etc/sysctl.conf
sysctl -p /etc/sysctl.conf
# 让从WireGuard来的流量能访问内网
iptables -t nat -A POSTROUTING -s 100.65.0.0/24 -d 192.168.100.0/24 -j MASQUERADE
# 或者如果要将所有外部流量转发到防火墙处理
iptables -t nat -A PREROUTING -i wg0 ! -d 192.168.100.0/24 -j DNAT --to-destination 192.168.100.10

把VPS的公网IP通过VPN隧道转发给其他设备
https://imoe.ac.cn/archives/ba-vpsde-gong-wang-iptong-guo-vpnsui-dao-zhuan-fa-gei-qi-ta-she-bei
作者
Li Ma
发布于
更新于
许可