How to get the IP prefix while we have subnet and IPv4 address using python-netaddr?

Amit Pal picture Amit Pal · May 30, 2012 · Viewed 18.1k times · Source

I am using python-netaddr library to work on IP Addresses and subnets. I read the full documentaion of netaddrd given: Netaddr documentation. But didn't found any solution to my problem. I have a IP Address and subnet i want to get prefix for that ip by using both of them. So that i can print all of the ip coming into the subnet.

For example:

Ip Address: 192.0.2.0
Subnet Network: 255.255.255.0

It should return the prefix which is : 24

Answer

Maria Zverina picture Maria Zverina · May 30, 2012

To get 24 you can use the following snippet

ip = IPNetwork('192.0.2.0/255.255.255.0')
print ip.prefixlen

But if you want list of all addresses in the subnet it's easier to use:

ip = IPNetwork('192.0.2.0/255.255.255.0')
list(ip)