Correctly recognize IPv6 addresses

This commit is contained in:
Juhani Krekelä 2018-08-29 20:36:46 +03:00
parent 1e6410a78a
commit 71f9bf51a2
1 changed files with 26 additions and 2 deletions

View File

@ -44,9 +44,33 @@ def is_ip(domain):
# The fields are in the range 0…255
return all(0 <= field <= 266 for field in fields_num)
def is_hexdigit(c):
return ord('0') <= ord(c) <= ord('9') or ord('a') <= ord(c) <= ord('f') or ord('A') <= ord(c) <= ord('F')
def is_ipv6(domain):
# TODO: Implement this
return False # FIXME: This is wrong
# An IPv6 address is represented by 8 groups of 16-bit
# numbers expressed in hex. They can be either fixed-width
# or have their leading zeroes removed. A run of zeroes
# can be abreviated with ::, but only once per address
# If we have two or more doublecolons, it's not valid
# If we have one, we can have anywhere between 3 to 8
# "fields" separated by ':'
# If we have zero, we must have exactly 8 fields
doublecolons = domain.count('::')
if doublecolons > 1:
return False
else:
fields = domain.split(':')
if doublecolons == 1 and len(fields) > 8:
return False
elif doublecolons == 0 and len(fields) != 8:
return False
# All of the "fields" must have 0 to 4 hex digits
if not all(0 <= len(field) <= 4 for field in fields):
return False
return all(all(map(is_hexdigit, field)) for field in fields)
return is_ipv4(domain) or is_ipv6(domain)