As I work a lot with network data, one of my favourite python modules is iplib. It takes care of quite a few of things I want to do with IP addresses but lacks a lot of functionality of perl's Net::Netmask which I relied on extensively when perl was my favourite language.
One of the iplib missing features is a method for sorting a list of IP addresses, or at the very least, a method for comparing two addresses.
Luckily this is easy enough to implement yourself in python using a customised sort function. See the Sorting Mini-HOW TO for a well written document on sorting in python.
Here is my attempt at a custom function for sorting IP addresses.
Sorted.
Update: A few people left comments which helped me realise how inefficient the above approach is. Take a look at the improved version.
One of the iplib missing features is a method for sorting a list of IP addresses, or at the very least, a method for comparing two addresses.
Luckily this is easy enough to implement yourself in python using a customised sort function. See the Sorting Mini-HOW TO for a well written document on sorting in python.
Here is my attempt at a custom function for sorting IP addresses.
import iplib
ips = ["192.168.100.56", "192.168.0.3", "192.0.0.192", "8.0.0.255"]
def ip_compare(x, y):
""" Compare two IP addresses. """
# Convert IP addresses to decimal for easy comparison
dec_x = int(iplib.convert(x, "dec"))
dec_y = int(iplib.convert(y, "dec"))
if dec_x > dec_y:
return 1
elif dec_x == dec_y:
return 0
else:
return -1
ips.sort(ip_compare) # Sort in place
print ips
['8.0.0.255', '192.0.0.192', '192.168.0.3', '192.168.100.56']
Sorted.
Update: A few people left comments which helped me realise how inefficient the above approach is. Take a look at the improved version.
Comments
I agree with Ben above, just store these as ints and use the built-ins. That has the additional advantage that all of your code except the display areas is IP6 compatible.
If you simply can't do that, I'd suggest at least expanding your data structure to include the converted int IP address so you only have to make the conversion once per IP.
If you can't do that, at least be concise!
import iplib
def ip_to_decimal(x):
return int(iplib.convert(x, "dec"))
def ip_compare(x, y):
""" Compare two IP addresses. """
return cmp(ip_to_decimal(x), ip_to_decimal(y))
[on preview: Blogger totally sucks for code samples - there's no code tag and no pre tag - WTF is one supposed to do?!
ips.sort(key=lambda x: iplib.convert(x, 'dec'))
(I just like to read through documentation sometimes ;)