Coverage for /Users/davegaeddert/Development/dropseed/plain/plain/plain/utils/ipv6.py: 22%

1 import ipaddress

2

3 from plain.exceptions import ValidationError

4

5

6 def 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.

11

12 Raise ValidationError if the address is invalid.

13

14 Replace the longest continuous zero-sequence with "::", remove leading

15 zeroes, and make sure all hextets are lowercase.

16

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.

22

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")

29

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)

34

35 return str(addr)

36

37

38 def 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