[Tutor] IP sorting

Karthik Gurumurthy karthikg@aztec.soft.net
Thu, 27 Dec 2001 10:04:26 +0530


sort is doing a string comparison of the ip addresses you have
which are infact strings in your list.

so '192.168.100.12' > '192.168.100.110'

because '12' > '110'

you have an option to specify a function object along with sort which would
do the comparison according to your needs
Something along the following lines should work.


def func(a,b):

	l1 = map(int,a.split('.'))
	l2 = map(int,b.split('.'))

	for i in range(len(l1)):
		first = l1[i]
		sec = l2[i]

		if first == sec:
			continue;
		elif first > sec:
			return 1
		else:
			return -1
	else:
		return 0



dead_bishop = ip_dictionary.keys()
dead_bishop.sort(func)

this should work.

karthik.



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
ccl
Sent: Thursday, December 27, 2001 7:58 AM
To: tutor@python.org
Subject: [Tutor] IP sorting


This may be somewhere, and I am just being lazy, but its something I need
to fix...

I am currently writing a script to analyze proxy server logs. One section
of the script scrubs out the IP addresses, counts them and sorts them and
prints them in a nice ordered way with the IP, then the number of hits.
(ie. "192.168.1.5 ----- 356 hits")

Basically, what I am doing is creating a dictionary with the IP as the key,
and the result of string.count() as the entry.

then I do...

dead_bishop = ip_dictionary.keys()
dead_bishop.sort()
for item in dead_bishop:
  print item," ---- ",ip_dictionary[item]," hits"


All is good, it works well, however it only sorts to the second place of
the last octet. For example...

192.168.100.118 --- 5 hits
192.168.100.119 --- 10 hits
192.168.100.12 --- 3 hits
192.168.100.120 --- 22 hits

How do I get the 192.168.100.12 to go where it supposed to (at the
beginning)?



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor