Home·Terminal commands

iptables

Networking

Usage

sudo iptables -L -n -v --line-numbers

Edits the live packet filter; rules are matched top to bottom and the first match wins, so a DROP appended after an ACCEPT never fires, the rules vanish at reboot unless saved, and setting the default policy to DROP before allowing port 22 locks you out of a remote machine.

Common flags

FlagMeaning
-L -n -v --line-numbersList the rules with counters and the numbers you need for -D.
-A <CHAIN>Append to the end of a chain, where an earlier rule may already have decided.
-I <CHAIN> 1Insert at the top, which is usually what you meant.
-D <CHAIN> <n>Delete rule number n.
-p tcp --dport 22Match protocol and destination port.
-s 10.0.0.0/8Match a source address or range.
-j ACCEPT|DROP|REJECTWhat to do with a matching packet.
-P <CHAIN> DROPSet the default policy, applied when no rule matched.

Examples

sudo iptables -L -n -v --line-numbers

Read the current rules before changing anything.

sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

Guarantee your own SSH access first.

sudo iptables-save > /etc/iptables/rules.v4

Make the rules survive a reboot.

When a connection fails, these narrow down how far it got — name not resolving, no route, or a blocked port.

How to read this

  • Square brackets [ ] mark a part you may leave out.
  • An ellipsis … means you can list more than one.
  • Flags are case-sensitive — in some commands -r and -R do different things.

Questions

Q. What does iptables do?

Edits the live packet filter; rules are matched top to bottom and the first match wins, so a DROP appended after an ACCEPT never fires, the rules vanish at reboot unless saved, and setting the default policy to DROP before allowing port 22 locks you out of a remote machine.

Q. How do I type it?

sudo iptables -L -n -v --line-numbers — square brackets mark the parts you can leave out.

Q. How many flags are worth knowing?

8 are listed here; the full set is in man iptables. This command sits under Networking.

Related commands

man page: man iptables