How to Get IPv4/IPv6 Address Range from CIDR in Python?
CIDR is short for Classless Inter-Domain Routing. It is used for allocating IP addresses and for IP routing. The CIDR number usually comes after the IP address and is preceded by a slash "/". For example, 220.127.116.11 would be expressed as 18.104.22.168/24 using a subnet mask of 255.255.255.0 (which has 24 network bits).
To get the starting and ending IP range from CIDR in Python, we can use Python's built-in module called ipaddress as shown in the example below:
import ipaddress def get_ip_range(cidr): net = ipaddress.ip_network(cidr) return net, net[-1] cidr = "22.214.171.124/23" ip_range = get_ip_range(cidr) start_ip = ip_range end_ip = ip_range print("Start ip = ", start_ip) print("End ip = ", end_ip)
The output of the above code is as follows:
Start ip = 126.96.36.199 End ip = 188.8.131.52