12

My purpose is to NAT (translate) all IP addresses that reach eth0 on all ports and protocols this way: 192.168.55.x -> 192.168.42.x (I have ip forwarding enabled and 192.168.42.0/24 subnetwork is on eth1). I can do this for one host per pair of lines like this, for example with x=20:

iptables -t nat -A PREROUTING -i eth0 -d 192.168.55.20 -j DNAT --to 192.168.42.20
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.42.20 -j SNAT --to 192.168.55.20

But I cannot find a way to translate all 253 possible hosts. I tried this:

iptables -t nat -A PREROUTING -i eth0 -d 192.168.55.0/24 -j DNAT --to 192.168.42.0-192.168.42.255
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.42.20/24 -j SNAT --to 192.168.55.0-192-168.55.255

This results in a random host translation. Useful for load balancing. But how to get a plain one-to-one translation?

Thank you.

1
  • You may be able to just use a for loop in the config file ... perhaps similar to what is suggested for ports here: here.
    – 0range
    Oct 17, 2016 at 13:33

1 Answer 1

21

From man iptables-extensions:

NETMAP
This target allows you to statically map a whole network of addresses onto another network of addresses. It can only be used from rules in the nat table.

So one rule only is needed:

iptables -t nat -A PREROUTING -d 192.168.55.0/24 -i eth0 -j NETMAP --to 192.168.42.0/24

If you also want connections initially started from the "42" net to be seen correctly, complete with this second rule:

iptables -t nat -A POSTROUTING -s 192.168.42.0/24 -o eth0 -j NETMAP --to 192.168.55.0/24
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.