Iptables – basic examples

Linux iptables (netfilter) is built-in firewall inside kernel

Check current iptables rules:

$ iptables --list

Check current iptables rules on NAT table:

$ iptables -t nat --list

Open tcp port 80 on iptables:

$ iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

Open tcp port 80 only for IP: 123.123.123.123

$ iptables -A INPUT -s 123.123.123.123 -p tcp -m tcp --dport 80 -j ACCEPT

Forwarding tcp port 8080 to IP 120.120.120.120 adddress:

$ iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 120.120.120.120:8080
$ iptables -A FORWARD -p tcp -d 120.120.120.120 --dport 8080 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

Please remember to enable ip forwarding inside Linux by using:

$ echo 1 > /proc/sys/net/ipv4/ip_forward

Enable ip forwarding permanently, please edit /etc/sysctl.conf, and add following line:

net.ipv4.ip_forward=1

Drop access to port 80:

$ iptables -A INPUT -p tcp -m tcp 80 -j DROP

Reject access with host unreachable:

$ iptables -A INPUT -p tcp -m tcp 80 -j REJECT --reject-with icmp-host-unreachable

You can also reject with different responses, like:
icmp-net-unreachable, icmp-port-unreachable, icmp-proto-unreachable, icmp-net-prohibited and icmp-host-prohibited

You can also create rate limit for connections, like protecing against ICMP flood for example:

$ iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 60/minute --limit-burst 120 -j ACCEPT
$ iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Linux Iptables

Updated on December 22, 2021

Choose which optional cookies this site may use. Your choice is remembered for 6 months on this device. Privacy and cookies policy