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

4

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
Karajan answered 30/5, 2012 at 9:24 Comment(7)
Where does 24 come from?Marciamarciano
Have you tried e.g. IPAddress('192.0.2.0/255.255.255.0')? You can get a list of all addresses in that subnet, with an example in the documentation you linked to.Aristate
Is /24 is a way of represent the mask 255.255.255.0 which is also 11111111.11111111.11111111.00000000Nadene
So you want to, given a dotted network mask, get the prefix length? The ip address does not make a difference here, does it?Slacks
IPAddress() does not support netmasks or subnet prefixes! That's why you need to use IPNetwork()Abjuration
@Marciamarciano I just gave a sample tested from onlineKarajan
@JoachimPileborg I did it shows : IPAddress() does not support netmasks or subnet prefixes! See documentation for details.Karajan
A
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)
Abjuration answered 30/5, 2012 at 9:35 Comment(0)
C
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
Caucasia answered 25/2, 2014 at 2:43 Comment(0)
C
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.

Caucasia answered 24/2, 2014 at 9:56 Comment(0)
P
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

Pocky answered 3/6, 2014 at 0:38 Comment(1)
Seems you could split it, bitwise-and it and join it back.Snip

© 2022 - 2024 — McMap. All rights reserved.