Given list of IPs
list_of_ips = ['10.0.0.10', '10.0.0.11', '10.0.0.12', '10.0.0.13', '10.0.0.40', '10.0.0.43', '10.0.0.44', '10.0.0.45', '10.0.0.46', '10.0.0.47', '10.0.0.48', '10.0.0.49', '10.0.0.50', '10.0.0.51', '10.0.0.52', '10.0.0.53', '10.0.0.54', '10.0.0.55', '10.0.0.56', '10.0.0.57', '10.0.0.58', '10.0.0.59', '10.0.0.60']
Want to collapse the list into range of IPs with dash if sequence of IPs in range or single IP.
Example:
output = ['10.0.0.10-10.0.0.13', '10.0.0.40', '10.0.0.43-10.0.0.60']
Here is the partially working code, for some reason I can't get the last range after 10.0.0.43 - 10.0.0.60
Not sure were why it is not adding
def compare_ips(ip1, ip2): last_octet1 = int(ip1.split('.')[-1]) # splits the ip and grabs the last octet last_octet2 = int(ip2.split('.')[-1]) # splits the ip and grabs the last octet if last_octet1 > last_octet2: return -1 if last_octet1 < last_octet2: if (last_octet2 - last_octet1) == 1: return 1 else: print("More then 1") return 99 return 0range, group = [], []for a, b in zip(list_of_ips, list_of_ips[1:]): check = compare_ips(a, b) if check == 1: group.append(a) continue elif check == 99: if not a in group: check2 = compare_ips(a, b) if check2 == 1: group.append(a) continue else: group.append(a) if not b in range: range.append(b) if len(group) > 1: range.append("{}-{}".format(group[0],group[-1])) group = []