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)
]
>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.