How to block IP and Ports with IPtables


How to block IP and/or Ports with IPtables under Linux?

Blocking an incoming port

First you have to know the port number which you want to block, for a list of port numbers you can use /etc/services as a reference.

The syntax is as follow (make sure you are root or have root privileges):

# /sbin/iptables -A INPUT -p tcp –destination-port PORT-NUMBER -j DROP

Use the following rule to block incoming port 80 (HTTP) and port 22 (SSH):

# /sbin/iptables -A INPUT -p tcp –destination-port 80 -j DROP
# /sbin/iptables -A INPUT -p tcp –destination-port 22 -j DROP

Blocking an incoming connection from an IP address

The syntax is as follow (make sure you are root or have root privileges):

# /sbin/iptables -A INPUT -s IP-ADDRESS -j DROP

For example you want to block IP address 8.8.8.8 to make a connection to your system:

# /sbin/iptables -A INPUT -s 8.8.8.8 -j DROP