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

I am using the python-netaddr library to work with IP addresses and subnets. I read the full netaddrd documentation: Netaddr documentation . But I did not find a solution to my problem. I have an IP address and subnet, I want to get a prefix for this ip using both of them. So that I can print the entire ip included in the subnet.

For instance:

Ip Address: 192.0.2.0
Subnet Network: 255.255.255.0

It should return the prefix which is : 24
+5
source share
4 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 to make the list of all addresses in the subnet easier to use:

ip = IPNetwork('192.0.2.0/255.255.255.0')
list(ip)
+6
source

:

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

"-", .

0
source

Subnet Mask: 255.255.255.0 Here's how to do it: 1. 1. 1. 0

255 ALL ALL 8-bits are included. i.e. ALL 1. AND 0 ALL 8-bits off. if you look at this mass subnet [255.255.255.0], the first 3 octets of ALL will be turned 'ON', and the last octet will be turned off. Thus, counting all the octets that are included in this case, 3 octets, we can say: 255.255.255.0 1. 1. 1.0 8 + 8 + 8 + 0 = 24

0
source

All Articles