Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 254
Amit Pal Avatar asked May 30 '12 09:05

Amit Pal


People also ask

How do I find the prefix of an IPv4 address?

In IPv4, the prefix (or network portion) of the address can be identified by a dotted-decimal netmask, commonly referred to as a subnet mask. For example, 255.255. 255.0 indicates that the network portion, or prefix length, of the IPv4 address is the leftmost 24 bits.

How do I find the subnet mask for an IP address in python?

The ipaddress. ip_network function can take any of the string formats that IPv4Network and IPv6Network can take, including the address/mask format. Since you're not actually passing the network address, but an address within that network with host bits set, you need to use strict=False .

How do you split an IP address in python?

# split function is used divide the string into smaller one with delimiter of dot. If user enters 192.168. 1.1, in this case whenever DOT is seen, string is divided into four different parts by using split function ip_address_split = ip_address. split(".")


1 Answers

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)
like image 125
Maria Zverina Avatar answered Sep 23 '22 18:09

Maria Zverina