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 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 -j DNAT --to
iptables -t nat -A POSTROUTING -o eth0 -s -j SNAT --to

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

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

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

From man iptables-extensions:

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 -i eth0 -j NETMAP --to

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 -o eth0 -j NETMAP --to
  • 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.