inet_aton similar function for IPv6
Asked Answered
B

1

9

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?

Burseraceous answered 11/5, 2012 at 20:50 Comment(0)
B
11

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'
Buckingham answered 11/5, 2012 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.