iptables-optimize is a python script that can optimize an iptables ruleset by reordering rules matching most often.


You can download it from its git repository:

git clone
cd iptables-optimize
sudo python install

or on Gentoo emerge it using the portage overlay as described here .

What does it do

This script takes an existing ruleset and reorders rules based on how much time they already matched (using iptables packet count). Rules matching are moved at the beginning of the ruleset to make them faster when the ruleset is evaluated by the kernel on a each new packet. To avoid breaking the ruleset, rule partly hidden by other rules won't get an higher priority. Though determining which rule hide which one is a bit a complicated due iptables overwhelming set of options. Currently evaluated options to determine if a rule hide an other one are:

  • Source address / destination address
  • Protocol, destination port.
  • Input / ouput interfaces.
  • State of the packet (NEW, ESTABLISHED ...)
  • Target of the rule. (Two rules with the same target are considered as not hiding themselves)

How to use it

The script can be applied on iptables ruleset exported via the iptables-save command, the generated ruleset can then be imported with the iptables-restore:

iptables-save -c > ruleset
iptables-optimize ruleset > optimized-ruleset

Check the generated ruleset, it can then be applied with:

iptables-restore -c < optimized-ruleset