[英]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 ): 我有一个用于存储IP地址的字段,并且我正在使用以下代码将IPv4地址转换为整数,因此可以将地址的可排序版本保存在单独的bigint字段中,以实现更自然的排序(基于此 ):
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? 我该如何处理对bigint字段来说太大的IPv6地址?
And is there a simple way to do the integer conversion for IPv6? 有没有一种简单的方法可以对IPv6进行整数转换? Python3 seems to provide this with the "ipaddress" module, but I'm using 2.7.
Python3似乎为此提供了“ ipaddress”模块,但我使用的是2.7。 I want to support the various ways of leaving zero's out of the address.
我想支持将地址保留为零的各种方法。
Update : I'm using Django 1.5 更新 :我正在使用Django 1.5
I ended up using this code to convert the IPs to integers: 我最终使用以下代码将IP转换为整数:
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 按照kroolik的建议,使用DecimalField有效
I believe I'd split IPv4 addresses on ., and sort as a list. 我相信我会在。上分割IPv4地址,并按列表排序。 Similarly for IPv6, I'd try splitting on :, and sorting them as a list too.
同样,对于IPv6,我会尝试在:上拆分,并将它们也作为列表进行排序。
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.
这样,如果确实发生更改,则更改不会分散在您的代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.