Installing and using ipset

ipset – a tool consisting of a kernel module, libraries and utility, allowing you to organize a list of networks, IP or MAC addresses, etc., which is very convenient to use for example with IPTables.

Installation command in Ubuntu:

sudo apt install ipset

Installation on CentOS:

sudo yum install ipset

I will give the possible types of list:
net (networks for example
ip (ip only, for example
mac (MAC addresses, for example 11:22:33:44:55:66)
port (ports, convenient when creating lists ip,port)
iface (network interfaces, convenient when creating lists of ip,iface)

Here are some examples of creating a list (where ixnfo is the name of the list):

ipset -N ixnfo nethash
ipset create ixnfo nethash
ipset create ixnfo hash:net
ipset create ixnfo hash:ip
ipset create ixnfo hash:ip,port
ipset create ixnfo hash:ip,iface
ipset create ixnfo hash:mac

ipset deletion example:

ipset destroy ixnfo

I will give examples of adding data to the lists:

ipset add ixnfo
ipset add ixnfo
ipset add ixnfo,80
ipset add ixnfo,udp:1812
ipset add ixnfo,eth0
ipset add ixnfo 11:22:33:44:55:66

An example of removing an item from the list:

ipset del ixnfo

If the same elements are added, for example, by scripts, and in order not to display extra messages that the element has already been added, add to the command “-exist”, for example:

ipset add ixnfo -exist

ipset will not add the same items to the list, if you add several identical items, there will still be one in the list.

Example of viewing lists:

ipset -L
ipset --list
ipset -L ixnfo

Counting the number of lines in the list, the second command with grep considers only IP addresses, which is convenient, since 7 lines with technical text are not counted (where ixnfo is the name of the list):

ipset -L | wc -l
ipset -L ixnfo | /bin/grep '\([[:digit:]]\{1,3\}\.\)\{3\}[[:digit:]]\{1,3\}' | /usr/bin/wc -l

You can rename the list like this:


Now when we have a list created, manually or it fills the script using ipset and iptables for example, it is very convenient to deny access to the server to all addresses that are in the list:

iptables -I INPUT -m set --match-set ixnfo src -j DROP

Or so (allow access to everyone except the addresses in the list):

iptables -I INPUT -m set ! --match-set ixnfo src -j ACCEPT

See also my articles:
The script for adding IP addresses from a file to ipset
Configure IPTables

Leave a comment

Leave a Reply