Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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(error_message, code="invalid")
  23. if unpack_ipv4 and addr.ipv4_mapped:
  24. return str(addr.ipv4_mapped)
  25. elif addr.ipv4_mapped:
  26. return "::ffff:%s" % str(addr.ipv4_mapped)
  27. return str(addr)
  28. def is_valid_ipv6_address(ip_str):
  29. """
  30. Return whether or not the `ip_str` string is a valid IPv6 address.
  31. """
  32. try:
  33. ipaddress.IPv6Address(ip_str)
  34. except ValueError:
  35. return False
  36. return True