TCP/IP Outbound round-robin load balancing with iptables

By | January 4, 2014

In reference to the solution article Iptables TCP/IP outbound syn rate limit, this guide touches on the same genre, that about controlling your outbound traffic rate.

Sometimes it is required that you load-balance your outbound connections over multiple IP’s on your system using iptables.
For example, say you have the following IP’s configured on your server:
– 192.168.0.1
– 192.168.0.2
– 192.168.0.3

The first outbound TCP/IP connection should use 192.168.0.1 as the source, the second connection should use 192.168.0.2 as the source, the third should use 192.168.0.3 and so on. This is especially useful with bulk mailing services, where you need to send thousands of emails over multiple IP’s as some email service providers place a limit on the amount of emails you can send to them within a certain time frame from one source IP. With TCP/IP outbound round-robin, you can send many more emails at the same time from the same system, each time pretending to come from a different source.

To setup, run the following commands:

iptables -t nat -A POSTROUTING -m state --state NEW -m statistic --mode nth --every 1 -j SNAT --to-source 192.168.0.1
iptables -t nat -A POSTROUTING -m state --state NEW -m statistic --mode nth --every 1 -j SNAT --to-source 192.168.0.2
iptables -t nat -A POSTROUTING -m state --state NEW -m statistic --mode nth --every 1 -j SNAT --to-source 192.168.0.3

Repeat each line for every static IP configured on your system (hundreds even!).
Remember to save your new firewall rules, for persistence across reboots:

service iptables save

The above command is valid on RHEL / CentOS Linux distributions.