Get all IP addresses from CIDR subnet in Python3

Published by Reza Rafati on

I was searching for a method to get all IP addresses from a CIDR subnet in Python3, and I was pleasantly surprised when I noticed that there is an inbuild library in Python3 which will do exactly that for you.

The Python3 library ‘ipaddress’ is build into Python3 and it works like a charm. You can ‘import ipaddress’ directly into your Python code, and use it further in your application.

How does it work

Lets say we have a CIDR, and we want to get all the IP addresses from that CIDR. In my code, I used the code snippet which provides back a list of the found IP addresses.

#works in Python3
import ipaddress
cidrx = ''
set1 = ipaddress.ip_network(cidrx)
ip_list=[str(ip) for ip in set1]
for ipv4 in ip_list:

The IP addresses are calculated by the Python code above, the calculated IP addresses are then stored in the ip_list list and the iteration will print each calculated IPv4 address to your terminal.

The list itself will look like this when printed to the terminal

Printed list of IPv4 addresses via the Python IPaddress library

The code itself can be adjusted in such, that you can work with the calculated IP addresses.

Have fun!

Some other resources that can help:

Share this information

Reza Rafati

Founder of