sorting on IP addresses

Sam Wun swun at esec.com.au
Mon Feb 5 17:42:42 EST 2001


Many thanks.
sam
chris at onca.catsden.net wrote:

> On Tue, 6 Feb 2001, Sam Wun wrote:
>
> > Hi,
> >
> > 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
>
> This may not be the fastest way, but it works, and its elegant :)
>
> import string
>
> def cmp_ipaddress ( ip1, ip2 ):
>         parts1 = map(lambda x:int(x), string.split(ip1,'.'))
>         parts2 = map(lambda x:int(x), string.split(ip2,'.'))
>         comparisons = map ( lambda x,y: cmp(x,y), parts1, parts2 )
>         return reduce ( lambda x,y: x or y, comparisons )
>
> ips = [ '203.21.254.89', '203.21.254.9' ]
>
> ips.sort ( cmp_ipaddress )
>
> print `ips`
>
> -> ['203.21.254.9', '203.21.254.89']
>
>    ("`-/")_.-'"``-._        Ch'marr, a.k.a.
>     . . `; -._    )-;-,_`)  Chris Cogdon <chmarr at furry.org.au>
>    (v_,)'  _  )`-.\  ``-'
>   _.- _..-_/ / ((.'       FC1.3: FFH3cmA+>++C++D++H++M++P++R++T+++WZ++Sm++
> ((,.-'   ((,/   fL               RLCT acl+++d++e+f+++h++i++++jp-sm++

--
Sam Wun                         Firewalls / Security
Senior Software Engineer        Electronic Commerce
eSec Limited                    Phone: +61 3 8371 5376
mailto:swun at eSec.com.au         C++/JAVA/UNIX/OOP/OOD


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010206/dd442030/attachment.html>


More information about the Python-list mailing list