Blocking an IP Address using iptables
1. Introduction
iptables is a powerful firewall utility available in Linux systems that allows administrators to control incoming and outgoing network traffic. One common use case is blocking traffic from a specific IP address to protect a server from malicious activity, repeated failed login attempts, or excessive requests.
This document outlines the process to:
- Check if an IP is already blocked.
- Add a new firewall rule to block it.
- Save the configuration to make it persistent after a reboot.
2. Prerequisites
Before performing these steps, ensure the following:
- Root or Sudo Access: You must have administrative privileges on the server.
- iptables Installed: Most Linux distributions (CentOS, RHEL, Fedora, Debian, Ubuntu) come with iptablespre-installed.
- Basic Command Line Knowledge: Familiarity with Linux terminal commands.
- The IP Address to Block: Ensure you have identified the correct IP to avoid blocking legitimate traffic.
3. Procedure
Step 1: Check if the IP is already blocked
iptables -L -n | grep <IP_address>
- Explanation:
- -Llists all current rules.
- -navoids DNS lookups and shows raw IP addresses.
- grepfilters the output for the specific IP.
 
- If no output appears, the IP is not currently blocked.
Step 2: Block the IP Address
iptables -A INPUT -s <IP_address> -j DROP
- Explanation:
- -A INPUTappends the rule to the INPUT chain (incoming traffic).
- -s <IP_address>specifies the source IP to block.
- -j DROPtells iptables to silently discard packets from that IP.
 
Step 3: Save the iptables Rules
iptables-save > /etc/sysconfig/iptables
- Explanation:
- iptables-saveoutputs the current firewall rules.
- Redirecting to /etc/sysconfig/iptablesensures the rules are applied automatically after a reboot.
 
4. Notes & Best Practices
- To remove a blocked IP: iptables -D INPUT -s <IP_address> -j DROP
- Always double-check the IP before blocking, to avoid disrupting legitimate connections.
- Consider using fail2banfor automated blocking of repeated offenders.
- For firewalld-based systems (CentOS 7+), use firewall-cmdinstead of directiptablesedits.
5. Conclusion
Blocking specific IP addresses using iptables is an effective way to mitigate certain types of malicious traffic and protect server resources. By following the above steps, administrators can quickly identify, block, and persist these rules, maintaining better control over inbound traffic.
