ipv6.py 1.4 KB

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