Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert ipv6 to an integer

Tags:

python

ipv6

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,

like image 673
Amir Avatar asked Aug 10 '12 02:08

Amir


1 Answers

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
like image 74
mhawke Avatar answered Oct 15 '22 08:10

mhawke