2017-01-30 03:07:50 +08:00
|
|
|
import ipaddress
|
2016-02-12 20:26:45 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def clean_ipv6_address(ip_str, unpack_ipv4=False,
|
2016-03-29 06:33:29 +08:00
|
|
|
error_message=_("This is not a valid IPv6 address.")):
|
2011-06-11 21:48:24 +08:00
|
|
|
"""
|
2017-01-30 03:07:50 +08:00
|
|
|
Clean an IPv6 address string.
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2017-01-30 03:07:50 +08:00
|
|
|
Raise ValidationError if the address is invalid.
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2017-01-30 03:07:50 +08:00
|
|
|
Replace the longest continuous zero-sequence with "::", remove leading
|
|
|
|
zeroes, and make sure all hextets are lowercase.
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
Args:
|
|
|
|
ip_str: A valid IPv6 address.
|
|
|
|
unpack_ipv4: if an IPv4-mapped address is found,
|
|
|
|
return the plain IPv4 address (default=False).
|
2014-08-02 21:14:13 +08:00
|
|
|
error_message: An error message used in the ValidationError.
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2017-01-30 03:07:50 +08:00
|
|
|
Return a compressed IPv6 address or the same value.
|
2011-06-11 21:48:24 +08:00
|
|
|
"""
|
2017-01-30 03:07:50 +08:00
|
|
|
try:
|
|
|
|
addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
|
|
|
|
except ValueError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(error_message, code='invalid')
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2017-01-30 03:07:50 +08:00
|
|
|
if unpack_ipv4 and addr.ipv4_mapped:
|
|
|
|
return str(addr.ipv4_mapped)
|
|
|
|
elif addr.ipv4_mapped:
|
|
|
|
return '::ffff:%s' % str(addr.ipv4_mapped)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2017-01-30 03:07:50 +08:00
|
|
|
return str(addr)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def is_valid_ipv6_address(ip_str):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return whether or not the `ip_str` string is a valid IPv6 address.
|
2011-06-11 21:48:24 +08:00
|
|
|
"""
|
2017-01-30 03:07:50 +08:00
|
|
|
try:
|
|
|
|
ipaddress.IPv6Address(ip_str)
|
|
|
|
except ValueError:
|
2016-02-12 20:26:45 +08:00
|
|
|
return False
|
2011-06-11 21:48:24 +08:00
|
|
|
return True
|