As one of the most powerful tools for firewall management in Linux systems, iptables is used to control incoming and outgoing network traffic. If you want to secure your server, block specific IP addresses, or allow only certain addresses, iptables commands are perfect for the job.
In this article, we explain how to block and allow IPs with iptables, and how to create basic rules in a detailed and understandable step-by-step manner.
What is IPTables? In Brief
IPTables is a firewall tool that runs in the Linux kernel and filters incoming/outgoing connections. It allows port and IP-based filtering by defining detailed rules on protocols such as TCP, UDP, and ICMP.
⚙️ Basic Concepts with IPTables
-
INPUT
: Requests coming to the server -
OUTPUT
: Requests going out from the server -
FORWARD
: Requests passing through another interface (router function) -
ACCEPT
: Allow -
DROP
: Silently block -
REJECT
: Block and send notification
Blocking Access to an IP Address (Banning)
Blocking a single IP address:
iptables -A INPUT -s 192.168.1.100 -j DROP
This command rejects all connections from the 192.168.1.100
address.
Subnet blocking (CIDR):
iptables -A INPUT -s 192.168.1.0/24 -j DROP
All connections from the specified network block are blocked.
✅ Granting Access to an IP Address
Allowing a specific IP for only a specific port:
iptables -A INPUT -p tcp -s 192.168.1.100 --dport 22 -j ACCEPT
This command allows SSH (port 22) connections from the 192.168.1.100
IP.
Blocking everyone except for specific IPs:
iptables -A INPUT -p tcp --dport 22 -j DROP
iptables -I INPUT -p tcp -s 192.168.1.100 --dport 22 -j ACCEPT
This order is important: first define DROP, then the exception rule ACCEPT.
Deleting or Clearing a Rule
Deleting a specific IP block:
iptables -D INPUT -s 192.168.1.100 -j DROP
Resetting all rules:
iptables -F
This command resets all rules, use with caution.
Making IPTables Rules Persistent
Ubuntu / Debian:
apt install iptables-persistent
netfilter-persistent save
CentOS / RHEL:
service iptables save
Or:
iptables-save > /etc/sysconfig/iptables
Tips to Avoid IPTables Errors
-
Allow your own IP first, then add blocking rules.
-
If your access is cut off after adding rules, plan physical/console access for recovery.
-
Check with the
iptables -L -n --line-numbers
command after each rule.
Conclusion
Managing IP addresses with IPTables provides a strong defense, especially against unwanted incoming connections. When applied correctly, it increases the security of your server, limits attacks, and allows you to take control of the network. However, careful configuration is essential; otherwise, you may lose your own access.