Python convert ipv6 to integer

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

Thanks,

+8
python ipv6
source share
5 answers

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

 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 
+14
source share

Do you want IPy .

 >>> IPy.IP('fe80::21b:77ff:fbd6:7860') IP('fe80::21b:77ff:fbd6:7860') >>> IPy.IP('fe80::21b:77ff:fbd6:7860').int() 338288524927261089654170743795120240736L >>> IPy.IP('fe80::fbd6:7860') IP('fe80::fbd6:7860') >>> IPy.IP('fe80::fbd6:7860').int() 338288524927261089654018896845572831328L 
+7
source share

Another solution using only stdlib:

 import socket import struct def int_from_ipv6(addr): hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, addr)) return (hi << 64) | lo 

Example

 >>> int_from_ipv6('fe80::fbd6:7860') 338288524927261089654018896845572831328L 

In Python 3.3+, you can use the ipaddress module :

 >>> import ipaddress >>> int(ipaddress.ip_address('fe80::fbd6:7860')) 338288524927261089654018896845572831328 
+5
source share

Using ipaddr module

 >>> import ipaddr >>> int(ipaddr.IPAddress('fe80::21b:77ff:fbd6:7860')) 338288524927261089654170743795120240736L 

Edit: thanks @JFSebastian for the best way

+4
source share

Maybe the netaddr you want.

 >>> from netaddr import * ip = IPNetwork('fe80::21b:77ff:fbd6:7860') >>> print ip.value 338288524927261089654170743795120240736 
+1
source share

All Articles