1
I assume you are only operating on one ip range like 127.0.0.*
if you want to work on multiple ip ranges the statement will become more complicated
so generally to sort a list of ip numbers by their last part (127.0.0.XXX), you can perform the following sort operation
sorted(my_ip_list, key=lambda x:int(x.split('.')[3]))
to return a new sorted list
or
my_ip_list.sort(cmp, key=lambda x:int(x.split('.')[3]))
for in-place sorting
to get the smallest gap in your ip list you can do the following list comprehension
sorted(
[ y for y in [ ''.join(['127.0.0.',str(x)]) for x in range(1,255) ]
if y not in my_ip_list ]
, key=lambda x:int(x.split('.')[3]))[0]
so what does it do?
letβs look at it from inside out:
my_ip_list := is list of ip adresses with deleted entries
next: the list comprehension
[ y for y in [ ''.join(['127.0.0.',str(x)]) for x in range(1,255) ]
if y not in my_ip_list ]
This will build a list of ip addresses from 127.0.0.1 to 127.0.0.255.
Then it will iterate over each created ip address and check if it is NOT in your real ip addresses list. If not, append that ip address to a new list.
In other words: we get a list of deleted ip addresses
Last step, sort the list of deleted ip addresses to find the smallest one. here you can see why my approach only works with a very limited set of ip addresses, as we sort only by the last part of the address (the 127.0.0.XXX part)
Anyway this last step follows the aforementioned idea of sorting ip ranges with sorted(...)
, or list.sort()