Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select every first and last IP Address of subnet ranges

I have a subnet 172.16.0.0/22 where I have four ranges 172.16.0.0 → 172.16.0.255 , 172.16.1.0 → 172.16.1.255, 172.16.2.0 → 172.16.2.255, and 172.16.3.0 → 172.16.3.255. I am using netaddr to find these ranges.

import netaddr

network = netaddr.IPNetwork(addr="172.16.0.0/22")

print(list(network))
# output
[
IPAddress("172.16.0.0"), 
IPAddress("172.16.0.1"),
...,
IPAddress("172.16.0.254"),
IPAddress("172.16.0.255"),
...,
IPAddress("172.16.1.0"),
IPAddress("172.16.1.1"),
...,
IPAddress("172.16.1.254"),
IPAddress("172.16.1.255"),
...,
IPAddress("172.16.2.0"),
IPAddress("172.16.2.1"),
...,
IPAddress("172.16.2.254"),
IPAddress("172.16.2.255"),
...,
IPAddress("172.16.3.0"),
IPAddress("172.16.3.1"),
...,
IPAddress("172.16.3.254"),
IPAddress("172.16.3.255"),
]

How can I pick every .1 and .254 of every range? i.e., How can I get an output that looks like this

[
    (172.16.0.1, 172.16.0.254), 
    (172.16.1.1, 172.16.1.254),
    (172.16.2.1, 172.16.2.254),
    (172.16.3.1, 172.16.3.254)
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

result = [(str(network[256 * r + 1]), str(network[256 * r + 254]))
          for r in range(len(network) // 256)]

Basically for every range (there are len(network) // 256 ranges) you take the element n. 1 (network[256 * r + 1]) and n. 254 (network[256 * r + 254]). Those elements are instances of class <class 'netaddr.ip.IPAddress'>: in order to convert them to strings you can just use the str built-in function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading