sorting ip address

1,177 views
Skip to first unread message

Matheus Suffi

unread,
Mar 31, 2015, 6:27:11 PM3/31/15
to web...@googlegroups.com
Hello,

im trying to sort an IP adddres list, this is the only result i getting
192.168.1.1
192.168.1.10
192.168.1.11

i want to list in that order:
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4

Any ideias ?

Niphlod

unread,
Mar 31, 2015, 6:47:16 PM3/31/15
to web...@googlegroups.com
use the power, luke!
aside from various networking libraries out there, the problem is rather simple....
what you're getting back is the "alphabetical order"  .
what you need instead is to sort every triplet as an integer.
In reality, python strings for ip addresses are good enough, if taken separately, i.e.
1 is lower than 10 even if "1" and "10" are strings.

so, to order your ip addresses, you just split every ip address by "."

given a list of
 
myips = [
'192.168.4.1',
'192.168.1.10',
'192.168.1.11',
]

what_you_want = sorted(myips, key=lambda x: x.split('.'))

Niphlod

unread,
Mar 31, 2015, 6:52:51 PM3/31/15
to web...@googlegroups.com
nope, wrong........... sorry, I reaally need some bed time ^_^

You NEED to convert triplets to integers before sorting.

no worries though...

what_you_want = sorted(myips, key=lambda x:tuple(map(int, x.split('.'))))



is the correct one.

Derek

unread,
Apr 2, 2015, 8:05:03 PM4/2/15
to web...@googlegroups.com
Wrong again. You really should just go to sleep.

First, you need to convert your IP addresses to decimal representation, then sort them.

import socket, struct

def ip2long_1(ip):
    return struct.unpack("!L", socket.inet_aton(ip))[0]

Niphlod

unread,
Apr 3, 2015, 3:19:04 AM4/3/15
to web...@googlegroups.com
maybe........what "list of ip addresses" gets sorted wrongly converting triplets to integers and right converting addresses to a decimal representation ?

Mirek Zvolský

unread,
Apr 3, 2015, 4:26:00 AM4/3/15
to web...@googlegroups.com
:)))

it works very well. The second one. Maybe tuple is not necessary:
what_you_want = sorted(myips, key=lambda x:map(int, x.split('.')))

But there are a little non-suitable testing values:  .4. versus .1.     :))




Dne středa 1. dubna 2015 0:27:11 UTC+2 Matheus Suffi napsal(a):

rharde...@gmail.com

unread,
Apr 5, 2015, 4:59:47 PM4/5/15
to web...@googlegroups.com
Try using the netaddr library...
Reply all
Reply to author
Forward
0 new messages