Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/utils/ipv6.py: 22%
19 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import ipaddress
3from django.core.exceptions import ValidationError
4from django.utils.translation import gettext_lazy as _
7def clean_ipv6_address(
8 ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")
9):
10 """
11 Clean an IPv6 address string.
13 Raise ValidationError if the address is invalid.
15 Replace the longest continuous zero-sequence with "::", remove leading
16 zeroes, and make sure all hextets are lowercase.
18 Args:
19 ip_str: A valid IPv6 address.
20 unpack_ipv4: if an IPv4-mapped address is found,
21 return the plain IPv4 address (default=False).
22 error_message: An error message used in the ValidationError.
24 Return a compressed IPv6 address or the same value.
25 """
26 try:
27 addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
28 except ValueError:
29 raise ValidationError(error_message, code="invalid")
31 if unpack_ipv4 and addr.ipv4_mapped:
32 return str(addr.ipv4_mapped)
33 elif addr.ipv4_mapped:
34 return "::ffff:%s" % str(addr.ipv4_mapped)
36 return str(addr)
39def is_valid_ipv6_address(ip_str):
40 """
41 Return whether or not the `ip_str` string is a valid IPv6 address.
42 """
43 try:
44 ipaddress.IPv6Address(ip_str)
45 except ValueError:
46 return False
47 return True