Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inet_aton similar function for IPv6

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?

like image 847
Sanket Lad Avatar asked May 11 '12 20:05

Sanket Lad


1 Answers

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'
like image 155
Nick Craig-Wood Avatar answered Oct 13 '22 02:10

Nick Craig-Wood