5

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
Amit Pal
  • 10,604
  • 26
  • 80
  • 160

4 Answers4

7

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)
Maria Zverina
  • 10,863
  • 3
  • 44
  • 61
4

With a given Netmask we can get the prefix with the function below:

def getPrefix(mask):
    prefix = sum([bin(int(x)).count('1') for x in mask.split('.')])
    return prefix
sebix
  • 2,943
  • 2
  • 28
  • 43
0
def getPrefix(binary):
    prefixCount=0
    for i in (str(binary)):
        if(i == '1'):
            prefixCount+=1
    return prefixCount

This would return your "Prefixcount" if subnet is converted into binary format and given in input.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
0

The subnetmask is : 255.255.255.0 This is how i c it: 1 . 1 . 1. 0

255 is ALL the 8-bits are turned on. ie. ALL 1's. And 0 is ALL the 8-bits are turned off. if you look at this subnetmask [255.255.255.0], the first 3 octets are ALL turned 'ON' while the last octet is turned 'OFF'.
Thus, counting all the octets that are ON in this case, 3 octets we can say: 255.255.255.0 1 . 1 . 1 .0 8 + 8 + 8 + 0 =24