Network
The iptables command
Configures the kernel firewall with rules that accept, reject or drop packets by source, destination, port and protocol. It is used to allow or block specific ports. Many recent distributions manage it through nftables or ufw.
Most useful options
-A <cadena>Appends a rule to the end of the chain (INPUT, OUTPUT or FORWARD).-I <cadena> [n]Inserts a rule at the top, or at position n.-D <cadena> <n>Deletes rule number n from the chain.-LLists the rules. With -n it does not resolve names, and with -v it shows counters.-p <protocolo>Protocol: tcp, udp or icmp. With --dport, the destination port.-j <acción>Action on the packet: ACCEPT, DROP or REJECT. DROP stays silent; REJECT replies with an error.-P <cadena> <acción>Default policy of the chain, for example -P INPUT DROP.Copy-ready examples
$ sudo iptables -L -n -vShows the rules with packet counters, without resolving names.Example output
Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 412 32K ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTAllows SSH. Add it before switching the policy to DROP, or you will be locked out.$ sudo iptables -A INPUT -s 203.0.113.0/24 -j DROPDrops everything arriving from that network, legitimate traffic included.$ sudo iptables -D INPUT 3Deletes the third rule in the INPUT chain.You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| iptables: No chain/target/match by that name. | The chain name, target or match module is misspelled, or the module is not loaded. | Write the targets in capitals (ACCEPT, DROP) and check the module with -m. |
| Permission denied (you must be root) | iptables needs root privileges to read and change the kernel rules. | Run it with sudo. |
| iptables: Chain already exists. | You are trying to create a chain that already exists, for example with -N. | Use iptables -L -n to inspect it or -F to flush it before reusing it. |
Typical mistakes
- Order matters: the first matching rule wins, so an earlier DROP cancels a later ACCEPT.
Differences from similar commands
Security
Setting a DROP policy without a rule that allows your SSH locks you out of the machine: add your port's rule first. Rules live in memory and do not survive a reboot; save them with iptables-save and restore them with iptables-restore, or with your distribution's persistence package.
FAQ
How do I delete all the rules?
iptables -F empties the chains, but does not change the default policy: to go back to ACCEPT, use -P INPUT ACCEPT.
Why does my rule have no effect?
Usually an earlier rule already matches, or the rule sits in another chain: INPUT is not FORWARD.
More Network commands
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course