You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ipv6.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import ipaddress
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import gettext_lazy as _
  4. def clean_ipv6_address(ip_str, unpack_ipv4=False,
  5. error_message=_("This is not a valid IPv6 address.")):
  6. """
  7. Clean an IPv6 address string.
  8. Raise ValidationError if the address is invalid.
  9. Replace the longest continuous zero-sequence with "::", remove leading
  10. zeroes, and make sure all hextets are lowercase.
  11. Args:
  12. ip_str: A valid IPv6 address.
  13. unpack_ipv4: if an IPv4-mapped address is found,
  14. return the plain IPv4 address (default=False).
  15. error_message: An error message used in the ValidationError.
  16. Return a compressed IPv6 address or the same value.
  17. """
  18. try:
  19. addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
  20. except ValueError:
  21. raise ValidationError(error_message, code='invalid')
  22. if unpack_ipv4 and addr.ipv4_mapped:
  23. return str(addr.ipv4_mapped)
  24. elif addr.ipv4_mapped:
  25. return '::ffff:%s' % str(addr.ipv4_mapped)
  26. return str(addr)
  27. def is_valid_ipv6_address(ip_str):
  28. """
  29. Return whether or not the `ip_str` string is a valid IPv6 address.
  30. """
  31. try:
  32. ipaddress.IPv6Address(ip_str)
  33. except ValueError:
  34. return False
  35. return True