How to sort IP addresses stored in dictionary in Python?

后端 未结 8 1721
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 08:32

I have a piece of code that looks like this:

ipCount = defaultdict(int)

for logLine in logLines:
    date, serverIp, clientIp = logLine.split(\" \")
    ipC         


        
8条回答
  •  长情又很酷
    2020-11-29 09:07

    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'
    

提交回复
热议问题