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
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.
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 .
# 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(".")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With