I have a piece of code that looks like this:
ipCount = defaultdict(int)
for logLine in logLines:
date, serverIp, clientIp = logLine.split(\" \")
ipC
if your application does lots of things like "find ips in range x", "sort by ip" etc its often more convenient to store the numeric value of the ip internally and work with this one.
from socket import inet_aton,inet_ntoa
import struct
def ip2long(ip):
packed = inet_aton(ip)
lng = struct.unpack("!L", packed)[0]
return lng
convert the number back into an ip using this function:
def long2ip(lng):
packed = struct.pack("!L", lng)
ip=inet_ntoa(packed)
return ip
>>> ip2long('192.168.1.1')
3232235777
>>> ip2long('1.2.3.4')
16909060
>>> long2ip(3232235777)
'192.168.1.1'
>>> long2ip(16909060)
'1.2.3.4'
how about not working with strings at all and instead convert each octet into integer, then passing it into 4 dimensional dictionary?
ClientIps[192][168][102][105]=1
ClientIps[192][168][99][11]=1
then it is easy to just sort an array by key, isnt it?
for key1, value in sorted(ClientIps.items()):
for key2, value in sorted(ClientIps[key1].items()):
for key3, value in sorted(ClientIps[key1][key2].items()):
for key4, value in sorted(ClientIps[key][key2][key3].items()):
print(key1, key2, key3, key4)
for speed reasons it may be beneficial to also compare simple python dictionary against OrderedDict
.