大网数据广告活动
服务器运维问答

How to hijack traffic to a port using iptables

· 52CE 我爱测

I have an application listening on port 2000. I want to proxy all traffic to this port (originating locally) to a different port, say 4000. Right now i am doing something like this. iptables -t nat -A OUTPUT -p tcp --dport 2000 -…

问题原文

原帖链接 · johne · CC BY-SA 3.0

I have an application listening on port 2000. I want to proxy all traffic to this port (originating locally) to a different port, say 4000.

Right now i am doing something like this.

iptables -t nat -A OUTPUT -p tcp --dport 2000 -d 127.0.0.1 -j DNAT --to-destination 127.0.0.1:4000

This works as long as there is nothing listening on 2000. if I telnet to 2000, traffic is routed to 4000 as expected. But if there is something listening on 2000, the traffic is not hijacked/proxied. Is there a way to achieve this?

已采纳解答

原帖链接 · kasperd · CC BY-SA 3.0

It looks like the nc version you are using uses IPv6 by default. When you have nc listening on port 2000 the client connects to that bypassing your IPv4-only DNAT rule.

When nothing is listening on port 2000 it still tries to connect to that using IPv6 but fails, and then falls back to IPv4 where the DNAT rule will send it to the instance listening on port 4000.

The best solution I can think of at the moment is to simply create equivalent rules for both IPv4 and IPv6:

iptables -t nat -A OUTPUT -p tcp --dport 2000 -d 127.0.0.1 -j DNAT --to-destination 127.0.0.1:4000
ip6tables -t nat -I OUTPUT -p tcp --dport 2000 -d ::1 -j DNAT --to-destination '[::1]:4000'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-06-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。