Coverage for /Users/davegaeddert/Development/dropseed/plain/plain/plain/utils/ipv6.py: 22%
18 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-16 22:03 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-16 22:03 -0500
1import ipaddress
3from plain.exceptions import ValidationError
6def clean_ipv6_address(
7 ip_str, unpack_ipv4=False, error_message="This is not a valid IPv6 address."
8):
9 """
10 Clean an IPv6 address string.
12 Raise ValidationError if the address is invalid.
14 Replace the longest continuous zero-sequence with "::", remove leading
15 zeroes, and make sure all hextets are lowercase.
17 Args:
18 ip_str: A valid IPv6 address.
19 unpack_ipv4: if an IPv4-mapped address is found,
20 return the plain IPv4 address (default=False).
21 error_message: An error message used in the ValidationError.
23 Return a compressed IPv6 address or the same value.
24 """
25 try:
26 addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
27 except ValueError:
28 raise ValidationError(error_message, code="invalid")
30 if unpack_ipv4 and addr.ipv4_mapped:
31 return str(addr.ipv4_mapped)
32 elif addr.ipv4_mapped:
33 return "::ffff:%s" % str(addr.ipv4_mapped)
35 return str(addr)
38def is_valid_ipv6_address(ip_str):
39 """
40 Return whether or not the `ip_str` string is a valid IPv6 address.
41 """
42 try:
43 ipaddress.IPv6Address(ip_str)
44 except ValueError:
45 return False
46 return True