5

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.

  • 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 '16 at 13:33
5

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
  • Thank you! It works just fine. Still, I don't know how I didn't notice this one. It's been weeks and I don't remember. Perhaps read only guides where NETMAP is not mentioned. I only skimmed iptables man page. Thanks for this precious entry! – Djee Nov 7 '16 at 14:44

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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