How to Use iptables in Linux
Learn how to configure IP packet filter rules in Linux with iptables for better network control.
The command iptables
enables administrators to configure the IP packet filter rules of the Linux kernel firewall. It is essentially a tool that controls the network traffic in a system by determining what packets of data get to stay, where they are directed, and which ones are not allowed.
With iptables
, you can define filters and rules based on IP addresses, protocols (such as TCP, UDP), ports, or a combination of these.
So, typically, iptables
is used for establishing, managing, and enforcing rules concerning incoming and outgoing network traffic in Linux, which helps in tasks such as Network Address Translation (NAT), packet filtering, and packet mangling. This makes it a crucial tool for network security, allowing control over which connections are permitted or denied at various points in the network.
Here are some ways to use the iptables
command:
1. List Rules
To list all the rules in the firewall, you can use the -L
option.
iptables -L
2. Block an IP Address
To block all incoming traffic from a specific IP address, you can use the -A
option to append a rule to a chain.
iptables -A INPUT -s 192.168.0.10 -j DROP
The command above blocks all incoming traffic from the IP address 192.168.0.10
.
3. Allow an IP Address
To allow all incoming traffic from a specific IP address, you can use the -A
option to append a rule to a chain.
iptables -A INPUT -s 192.168.0.10 -j ACCEPT
The command above allows all incoming traffic from the IP address 192.168.0.10
.
4. Block a Port
To block all incoming traffic on a specific port, you can use the -A
option to append a rule to a chain.
iptables -A INPUT -p tcp --dport 80 -j DROP
The command above blocks all incoming traffic on TCP
port 80
.
5. Allow a Port
To allow all incoming traffic on a specific port, you can use the -A
option to append a rule to a chain.
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
The command above allows all incoming traffic on TCP
port 80
.
6. Delete a Rule
To delete a rule, you can use the -D
option followed by the chain and rule number.
iptables -D INPUT 1
The command above deletes the first rule in the INPUT chain.
7. Flush All Rules
To remove all rules, you can use the -F
option.
iptables -F
8. Block a Specific Service
If you want to block a specific service, you can specify the service name instead of the port number.
iptables -A INPUT -p tcp --dport ssh -j DROP
More Linux commands:
Directory Operations | rmdir · cd · pwd · exa · ls |
File Operations | cat · cp · dd · less · touch · ln · rename · more · head |
File System Operations | chown · mkfs · locate |
Networking | ping · curl · wget · iptables · mtr |
Search and Text Processing | find · grep · sed · whatis · ripgrep · fd · tldr |
System Information and Management | env · history · top · who · htop · glances · lsof |
User and Session Management | screen · su · sudo · open |