Reputation: 89
I have a list containing hundreds of ip addresses and masks in this format:
['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
I would like to convert this list to this format:
['10.10.10.0/24', '10.10.20.0/26']
Here is my code:
# List already containing all ip/mask (format: 10.10.10.0/255.255.255.0') shown above
print ip_mask_list
#hardcoded mask for testing
netmask = "255.255.248.0"
#convert mask to CIDR
cidr = sum([bin(int(x)).count('1') for x in netmask.split('.')])
print cidr # prints 21
I can convert a mask to CIDR but how would I do it so instead of passing hardcoded netmask variable, I can pass ip_mask_list
and it goes thru all masks and convert the to CIDR as shown above. Maybe create a next list where all 255.x.x.x
are converted to /xx
.
Thanks
Damon
Upvotes: 0
Views: 2261
Reputation: 463
This one splits the original IP address in an IP and a mask part. The IP Address is used as before while the cidr_suffix
is calculated based on the number of set bits in the ip_mask
.
ips = ['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
def append_cidr_suffix(full_ip):
address_and_mask = full_ip.split('/')
prefix = address_and_mask[0]
ip_mask = address_and_mask[1]
suffix = sum(bin(int(sub_part)).count('1') for sub_part in ip_mask.split('.'))
return prefix + '/' + str(suffix)
cidr_ips = [append_cidr_suffix(i) for i in ips]
Upvotes: 0
Reputation: 71451
You can use regex:
import re
s = ['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
final_ips = ['{}/{}'.format(a, sum([bin(int(x)).count('1') for x in b.split('.')])) for a, b in map(lambda x:re.findall('[\d\.]+', x), s)]
Output:
['10.10.10.0/24', '10.10.20.0/26']
Upvotes: 1