How long does it take for an iptables rule to apply?

iptables rules take effect immediately.

Since this script appends, there may be a rule before this that says to automatically allow the hosts you are trying to block. iptables reads rules top to bottom, and breaks as soon as it finds a match (so if you had something that said 'allow badhostx' and then next line was 'drop badhostx', it would never drop since the rule was already matched for that host.

If you're using the -A in a script you may want to flush your tables before (iptables --flush), to ensure that the rules are exactly as you apply them in the script ( but also make sure you have ALL the rules in that script).

Another option instead of running that script is to get the rules you want working, then do either "service iptables save" or "/etc/init.d/iptables save". Hope this helps.


iptables rules take effect immediately. Because your script is Appending (-A) to the INPUT and OUTPUT chains, your rules are being added to the end of those chains. If you have other terminating rules that precede these rules, then they will take effect (and later rules will not).

For example, it is very common to have a -m state --state ESTABLISHED,RELATED -j ACCEPT rule early in INPUT/OUTPUT chains, and that rule will take effect in precedence to any rules that come after it. That rule allows established connections to continue, even if they are to/from IP addresses that you have added to your firewall via your script.

If you do have an ESTABLISHED,RELATED rule in your INPUT/OUTPUT chains (or some other rule that is overriding later rules), then you'll either have to accept that your new rules many not take effect immediately, or you can have your script insert the IP-address DROP rules before the ESTABLISHED,RELATED rule. This can be accomplished by changing your script to Insert (-I) rather than Append (-A) your IP-address DROP rules, e.g.

iptables -I INPUT -s $1 -j DROP
iptables -I OUTPUT -d $1 -j DROP

You must add your rules at the beginning of filter table. So you must use -I (insert) instead of -A (append)