python convert ipv6 to an integer

Amir picture Amir · Aug 10, 2012 · Viewed 10.8k times · Source

Is there any package or easy way to convert an ipv6 to an integer? The algorithm should be a little smart to understand the ipv6 short formats. Before I start to write my own code , I just wonder if anyone knows a package that can do the job?

Thanks,

Answer

mhawke picture mhawke · Aug 10, 2012

You can do this with some help from the standard Python socket module. socket.inet_pton() handles IPV6 short form without any trouble.

import socket
from binascii import hexlify

def IPV6_to_int(ipv6_addr):
    return int(hexlify(socket.inet_pton(socket.AF_INET6, ipv6_addr)), 16)

>>> IPV6_to_int('fe80:0000:0000:0000:021b:77ff:fbd6:7860')
338288524927261089654170743795120240736L
>>> IPV6_to_int('fe80::021b:77ff:fbd6:7860')
338288524927261089654170743795120240736L