简体   繁体   中英

Sorting IPv4 and IPv6 address in a Database

I have a field for storing IP addresses and I'm using this code to convert an IPv4 address to an integer so I can save a sortable version of the address in a separate bigint field to achieve more natural sorting (based on this ):

octets = ip.split('.')
return (int(octets[0]) * 256**3) + (int(octets[1]) * 256**2) + (int(octets[2]) * 256) + (int(octets[3]))

How can I do something similar with IPv6 addresses which is too big for a bigint field?

And is there a simple way to do the integer conversion for IPv6? Python3 seems to provide this with the "ipaddress" module, but I'm using 2.7. I want to support the various ways of leaving zero's out of the address.

Update : I'm using Django 1.5

I ended up using this code to convert the IPs to integers:

import struct, socket

try:
    return struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip))[0]
except socket.error:
    try:
        hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, ip))
        return (hi << 64) | lo
    except socket.error:
        return 0

Using a DecimalField worked, as recommended by kroolik

I believe I'd split IPv4 addresses on ., and sort as a list. Similarly for IPv6, I'd try splitting on :, and sorting them as a list too.

And wrapping this up as a class would probably be a good idea, in case the behavior needs to change someday. That way, if it does change, the changes aren't scattered across your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM