sorting on IP addresses

Mark Pilgrim f8dy at diveintopython.org
Wed Mar 7 01:57:35 EST 2001


in article mailman.983939410.22287.python-list at python.org, Justin Sheehy at
justin at iago.org wrote on 3/6/01 11:29 PM:

> Sam Wun <swun at esec.com.au> writes:
> 
>> Does anyone know what is the quickly way to sort a list of IP addresses?
>> 
>> ie. 203.21.254.89 should be larger than 203.21.254.9
> 
> Convert to longs and sort on those values?
> 
> Not all that quick, I suppose, but I don't know of a faster correct way.

I could have sworn this was discussed about a month ago, but I can't find it
on groups.google.com (damn you Googja!).  Several methods were bandied
about, including custom sort functions passed to .sort().  After some timing
tests, the fastest appears to be munging the data with the magical
socket.inet_aton() function so you can do the sort natively, then munging it
back:

>>> import socket
>>> ips = ['127.0.0.1', '198.162.0.1', '10.1.2.5', '10.1.2.4']
>>> tempips = [socket.inet_aton(ip) for ip in ips]
>>> tempips
['\177\000\000\001', '\306\242\000\001', '\012\001\002\005',
'\012\001\002\004']
>>> tempips.sort()
>>> tempips
['\012\001\002\004', '\012\001\002\005', '\177\000\000\001',
'\306\242\000\001']
>>> [socket.inet_ntoa(ip) for ip in tempips]
['10.1.2.4', '10.1.2.5', '127.0.0.1', '198.162.0.1']

hang-around-long-enough-and-you-can-look-smart-by-recycling-other-people's-c
ode-ly,
-M
You're smart; why haven't you learned Python yet?
http://diveintopython.org/






More information about the Python-list mailing list