How to block only one IP using iptables?

Hi friends,

I have a linux machine without iptables running and we have a new requirement to block a remote machine ( IP = 172.1.1.1 ) completely accessing our linux machine in both directions. So I need to allow "everything" except that IP address. So i tried below:

If I set the below in /etc/sysconfig/iptables file and do service iptables restart then everything is allowed (included the blocked IP)

# Default IPtables config
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [26:8868]

-A INPUT -j ACCEPT
-A OUTPUT -j ACCEPT

-A INPUT --src 172.1.1.1 -j REJECT
-A OUTPUT --dst 172.1.1.1 -j REJECT

COMMIT

If I try the below then it blocks everything

# Default IPtables config
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [26:8868]

-A INPUT --src 172.1.1.1 -j REJECT
-A OUTPUT --dst 172.1.1.1 -j REJECT

-A INPUT -j ACCEPT
-A OUTPUT -j ACCEPT


COMMIT

I'm new to iptables and not sure what am I doing wrong, appreciate if any expert could help me out here please :slight_smile:

your 3rd,4th & 5th lines are culprits. Try this:

# Default IPtables config
*filter

-A INPUT --src 172.1.1.1 -j REJECT
-A OUTPUT --dst 172.1.1.1 -j REJECT

-A INPUT -j ACCEPT
-A OUTPUT -j ACCEPT

COMMIT
1 Like

Thanks, that seems to have solved my prob but i need more tests to do to ensure. Is there any tool or software or anything that can help me setup iptables easily? somehow I find iptables very uncomfortable :frowning:

In order to block an IP on your Linux server you need to use iptables tools (administration tool for IPv4 packet filtering and NAT) and netfilter firewall. First you need to log into shell as root user. To block an IP address you need to type the iptables command as follows:

Syntax to block an IP address under Linux

iptables -A INPUT -s IP-ADDRESS -j DROP

Replace IP-ADDRESS with your actual IP address. For example, if you wish to block an ip address 65.55.44.100 for whatever reason then type the command as follows:

# iptables -A INPUT -s 65.55.44.100 -j DROP

If you have IP tables firewall script, add the above rule to your script.

If you just want to block access to one port from an ip 65.55.44.100 to port 25 then type command:

# iptables -A INPUT -s 65.55.44.100 -p tcp --destination-port 25 -j DROP

The above rule will drop all packets coming from IP 65.55.44.100 to port mail server port 25.

CentOS / RHEL / Fedora Block An IP And Save It To Config File

Type the following two command:

# iptables -A INPUT -s 65.55.44.100 -j DROP
# service iptables save