Inet_aton similar function for IPv6

I use inet_atonto convert IPv4 IP (216.12.207.142) to line 3624718222. For this, I use the following code:

ip_dec = unpack('>L', inet_aton(ip))[0]

Now I need to convert IPv6 ip 2001: 23 :: 207: 142 to a similar string. This gives me an error as it is not an IPv4 address. How can i do this?

+5
source share
1 answer

This is the code I used for this purpose before. Note that it returns an integer of 128 bits, not a string (the integer is more useful in general)

from socket import inet_pton, AF_INET6
from struct import unpack

def ip6_to_integer(ip6):
    ip6 = inet_pton(AF_INET6, ip6)
    a, b = unpack(">QQ", ip6)
    return (a << 64) | b

And testing him

>>> ip6_to_integer("2001:23::207:142")
42540490934961530759802172199372521794L

Or as a string, if necessary!

>>> str(ip6_to_integer("2001:23::207:142"))
'42540490934961530759802172199372521794'
+6
source

All Articles