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)
]
CodePudding user response:
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.
CodePudding user response:
Checking the last octate in each IP Address to see if they are either of the desired numbers. I like this solution more as it uses only the netaddr
object structure.
[n for n in network if n.words[-1] in [1, 254]]
CodePudding user response:
I haven't tried this with a netaddr object but the code should also run as is because I covert the addresses to strings. It's not exactly what you wanted though. The addresses, per range are saved in lists.
network = [
"172.16.0.0","172.16.0.1","172.16.0.254","172.16.0.255","172.16.1.0",
"172.16.1.1","172.16.1.254","172.16.1.255","172.16.2.0","172.16.2.1",
"172.16.2.254","172.16.2.255","172.16.3.0",
"172.16.3.1","172.16.3.254","172.16.3.255",
]
def get_adress(network):
output,tmp = [],[]
for ad in network:
ad_str = str(ad)
if ad_str.endswith('.1') or ad_str.endswith('.254'):
tmp.append(ad_str)
if len(tmp)==2:
output.append(tmp)
tmp= []
return(output)
output= get_adress(network)
print(output)
>>[['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']]
Edit
This now has the addresses as tuples in a list.
def get_adress(network):
one,two = [],[]
for ad in network:
ad_str = str(ad)
if ad_str.endswith('.1'):
one.append(ad_str)
elif ad_str.endswith('.254'):
two.append(ad_str)
return(list(zip(one, two)))
output= get_adress(network)
output
>>[('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')]