Linux iptables Command
Linux iptables Command
The iptables
command in Linux is used to configure, maintain, and inspect the tables of IP packet filter rules in the Linux kernel firewall. It’s a powerful tool used for network traffic filtering and Network Address Translation (NAT).
🔰 Basic Syntax
$ iptables [OPTIONS] ACTION CHAIN RULE_SPECIFICATION
- ACTION –
-A
(append),-I
(insert),-D
(delete),-L
(list),-F
(flush) - CHAIN –
INPUT
,OUTPUT
,FORWARD
,PREROUTING
,POSTROUTING
- RULE_SPECIFICATION – Matches and targets like source, destination, protocol, ports, etc.
🔧 Commonly Used Chains
Chain | Description |
---|---|
INPUT | Incoming packets to the local system |
OUTPUT | Outgoing packets from the local system |
FORWARD | Packets being routed through the system |
PREROUTING | Used to alter packets as they arrive |
POSTROUTING | Used to alter packets before they leave |
✅ Common iptables Examples
List All Rules
$ sudo iptables -L -v -n
Allow Incoming SSH (Port 22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Block an IP Address
iptables -A INPUT -s 192.168.1.100 -j DROP
Allow Traffic from a Specific IP
iptables -A INPUT -s 10.0.0.5 -j ACCEPT
NAT Example (Masquerading for Internet Sharing)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Flush All Rules
iptables -F
🔒 Save iptables Rules
For Debian/Ubuntu:
sudo iptables-save > /etc/iptables/rules.v4
For RHEL/CentOS:
service iptables save
🛑 Important Notes
- Rules are checked top-down until a match is found.
iptables
rules do not persist after reboot unless saved.- Consider using
iptables-save
andiptables-restore
for persistence.