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

change source address of outgoing traffic destined to second network alias of source host

· 52CE 我爱测

I have following setup: ip addr : 2: ens4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 link/ether 01:12:23:34:45:5f brd ff:ff:ff:ff:ff:ff inet xxx.xxx.xxx.xxx/24 brd xxx.xxx.xxx.xxx …

问题原文

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

I have following setup:

ip addr:

2: ens4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 01:12:23:34:45:5f brd ff:ff:ff:ff:ff:ff
    inet xxx.xxx.xxx.xxx/24 brd xxx.xxx.xxx.xxx scope global ens4
       valid_lft forever preferred_lft forever
    inet 192.168.0.2/24 scope global ens4:1
       valid_lft forever preferred_lft forever
    inet 192.168.0.3/24 scope global secondary ens4:2
       valid_lft forever preferred_lft forever

I would like to have all traffic from 192.168.0.2 destined to 192.168.0.3 to show as if the source was 192.168.0.3.

The reason is I have speciffic configuration on postgres that I cannot change. This postgres is only accepting connections when source is 192.168.0.3, so if source becomes 192.168.0.2 then connection will be refused.

The above questions is result of answer received here: How to add ip route to route traffic through interface when destination is also that interface (it is not possible to change source IP address with static routes when two aliases are configured within the same network)

The answer to following question seems to be related to my question although it does not result in rule being added: https://unix.stackexchange.com/questions/243451/iptables-change-local-source-address-if-destination-address-matches

I already tried following nat rules:

iptables -t nat -A POSTROUTING -o ens4 -j MASQUERADE
iptables -A FORWARD -i ens4 --source 192.168.0.2/32 -o 192.168.0.3 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i ens4 --source 192.168.0.2/32 -o 192.168.0.3 -j ACCEPT

Above derived from here: http://www.revsys.com/writings/quicktips/nat.html

已采纳解答

原帖链接 · Alexander Tolkachev · CC BY-SA 3.0

I've checked answer that you mentioned in your question and tried to configure iptables like it was mentioned there. Tested with nginx on my virtual machine with CentOS and it works.

Try to use this rule:

iptables -t nat -A POSTROUTING --destination 192.168.0.3/32 -j SNAT --to-source 192.168.0.3

In my case this rule work even with disabled IP Forwarding, so try it.

Update:

For all outgoing traffic you shoud use rule:

iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.0.3

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

资料来源与适用范围

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

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

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