Extract ipv6 prefix in python

Given either a binary or a string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?

Is there a library that will do this for me, or will I have to:

  • convert address from string to int (inet_ntop)
  • Strike out the prefix
  • Convert prefix back to binary
  • Convert binaries to string (inet_ntop)
+1


source to share


2 answers


See http://code.google.com/p/ipaddr-py/

With this you can do



py> p=ipaddr.IPv6("2001:888:2000:d::a2")
py> p.SetPrefix(64)
py> p
IPv6('2001:888:2000:d::a2/64')
py> p.network_ext
'2001:888:2000:d::'

      

and etc.

+2


source


Using python netaddr library :



>>> from netaddr.ip import IPNetwork, IPAddress
>>> IPNetwork('2001:888:2000:d::a2/64').network
2001:888:2000:d::

      

0


source







All Articles