Quick Reference

Cheatsheets

Practical command references for Linux, networking, servers, containers, databases, and more.

Cheatsheet#ipset-cheatsheet

IPSet Cheatsheet

ipset is a companion application for the iptables Linux firewall. It allows you to setup, maintain, and inspect so-called "IP sets" - arrays of IP addresses, MAC addresses, or port numbers. It is extremely fast for matching thousands of IPs compared to sequential iptables rules.

Installation

sudo apt install ipset    # Debian/Ubuntu
sudo dnf install ipset    # RHEL/CentOS

Basic Operations

# Create a set for IP addresses
sudo ipset create blacklist hash:ip
 
# Create a set for network subnets
sudo ipset create bad_subnets hash:net
 
# List all sets
sudo ipset list
 
# Destroy a specific set
sudo ipset destroy blacklist
 
# Flush (empty) a set
sudo ipset flush blacklist

Modifying Sets

# Add an IP to the set
sudo ipset add blacklist 192.168.1.50
 
# Add a subnet
sudo ipset add bad_subnets 10.0.0.0/8
 
# Test if an IP is in the set
sudo ipset test blacklist 192.168.1.50
 
# Delete an IP from the set
sudo ipset del blacklist 192.168.1.50

Using IPSet with Iptables

Once your set is created, you can reference it in a single iptables rule.

# Drop all incoming traffic from IPs in the 'blacklist' set
sudo iptables -A INPUT -m set --match-set blacklist src -j DROP

Saving and Restoring

Sets are lost on reboot. You must save and restore them.

# Save sets to a file
sudo ipset save > /etc/ipset.conf
 
# Restore sets from a file
sudo ipset restore < /etc/ipset.conf