Question

I am using inet_aton to convert IPv4 IP(216.12.207.142) to a string 3624718222. I use the following code for that:

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

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

Was it helpful?

Solution

This is the code I've uses for the purpose before. Note that it returns a 128 bit integer rather than a string (an 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 it

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

Or as a string if you must!

>>> str(ip6_to_integer("2001:23::207:142"))
'42540490934961530759802172199372521794'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top