How to use iptables with Practical Examples

How to use iptables with Practical Examples


Iptables is a built‑in Linux firewall utility that controls network traffic by applying filtering rules. It is used by system administrators to block unwanted access, allow specific traffic, and secure servers from network attacks. 


iptables checks every network packet and applies rules to decide whether to allow, block, or modify it. The decision process is based on three key concepts: Tables, Chains, and Rules.


Tables define the type of packet processing.

Common Tables:

  1. filter – Default table for packet filtering.
  2. nat – Network Address Translation for routing and port forwarding.
  3. mangle – Modifies packet headers.
How to use iptables

Syntax:

sudo iptables -t -j

Examples:

  • filter table – Block Telnet traffic:
  • sudo iptables -t filter -A INPUT -p tcp –dport 23 -j DROP
  • nat table – Redirect HTTP to port 3128:
  • sudo iptables -t nat -A PREROUTING -p tcp –dport 80 -j REDIRECT –to-port 3128
  • mangle table – Change TOS value for SSH:
  • sudo iptables -t mangle -A OUTPUT -p tcp –dport 22 -j TOS –set-tos 0x10

Chains are lists of rules that packets pass through.

Common Chains:

  • INPUT – Traffic to the local machine.
  • OUTPUT – Traffic from the local machine.
  • FORWARD – Traffic passing through the machine.
how to use iptables

Syntax:

Examples:

  • INPUT – Allow SSH traffic:
  • sudo iptables -A INPUT -p tcp –dport 22 -j ACCEPT
  • OUTPUT – Block outgoing pings:
  • sudo iptables -A OUTPUT -p icmp –icmp-type echo-request -j DROP
  • FORWARD – Allow forwarding between subnets:
  • sudo iptables -A FORWARD -s 192.168.1.0/24 -d 192.168.2.0/24 -j ACCEPT

Rules specify conditions and actions for packets.

Syntax:

Examples:

  • Allow HTTP traffic:
  • sudo iptables -A INPUT -p tcp –dport 80 -j ACCEPT
  • Block specific IP:
  • sudo iptables -A INPUT -s 203.0.113.45 -j DROP
  •  
  • Log dropped packets:
  • sudo iptables -A INPUT -j LOG –log-prefix “Dropped Packet: “

Useful Commands

  • View rules:
  • sudo iptables -L -n -v
  • Delete a rule:
  • sudo iptables -D INPUT
  • Save rules:
  • sudo iptables-save > /etc/iptables/rules.v4

Read related: https://blog.vcclhosting.com/what-are-iptables-and-how-it-works/: How to use iptables with Practical Examples



Source link