V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
laqow
V2EX  ›  Linux

请教如何设置 iptables 将 localhost 某端口产生的数据转发到另一个 IP 的端口上?

  •  
  •   laqow · 2020-02-28 17:21:57 +08:00 · 3721 次点击
    这是一个创建于 1490 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我用 frp 建了个隧道,远程客户端装在 linux 的路由上,出口设在路由 127.0.0.1:12345,这个路由有另一个 IP 192.168.10.3,我希望走 127.0.0.1:12345 的数据能够无损转发到网关 192.168.10.1:54321 上,实现两个端口的互通(效果相当于把隧道出口挪到 192.168.10.1:54321 上),应该如何设置路由的 iptables 实现这个功能?

    个人理解是设一个-t nat -A OUTPUT 转发和-t nat -A POSTROUTING 的转发,但没能成功

    4 条回复    2021-04-06 15:23:10 +08:00
    Wang1993
        1
    Wang1993  
       2020-02-28 17:54:51 +08:00
    刚解决了类似的问题,下面的命令试试:
    sudo sysctl -w net.ipv4.conf.all.route_localnet=1
    sudo iptables -t nat -A OUTPUT -m addrtype --src-type LOCAL --dst-type LOCAL -p tcp --dport 12345 -j DNAT --to 192.168.10.1:54321
    sudo iptables -t nat -A POSTROUTING -m addrtype --src-type LOCAL --dst-type UNICAST -j MASQUERADE
    laqow
        2
    laqow  
    OP
       2020-02-29 01:24:05 +08:00
    谢谢,用的 openwrt,iptables 好像不支持-m addrtype --src-type LOCAL 这些,后面写成下面这样可以了,请看看有没有什么问题:
    sysctl -w net.ipv4.conf.all.route_localnet=1
    iptables -t nat -A OUTPUT -d 127.0.0.1 -p tcp --dport 12345 -j DNAT --to 192.168.10.1:54321
    iptables -t nat -A POSTROUTING -d 192.168.10.1 -p tcp -j MASQUERADE
    laqow
        3
    laqow  
    OP
       2020-02-29 01:24:32 +08:00
    @Wang1993 谢谢,用的 openwrt,iptables 好像不支持-m addrtype --src-type LOCAL 这些,后面写成下面这样可以了,请看看有没有什么问题:
    sysctl -w net.ipv4.conf.all.route_localnet=1
    iptables -t nat -A OUTPUT -d 127.0.0.1 -p tcp --dport 12345 -j DNAT --to 192.168.10.1:54321
    iptables -t nat -A POSTROUTING -d 192.168.10.1 -p tcp -j MASQUERADE
    kele1997
        4
    kele1997  
       2021-04-06 15:23:10 +08:00
    感谢,感谢
    原来 127.0.0.1 上的请求不只要 DNAT,还要使用 MASQUERADE 进行 SNAT 转换
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1130 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:53 · PVG 06:53 · LAX 15:53 · JFK 18:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.