Skip to content

Commit 4154d1f

Browse files
committed
Improve IPv6 validation
fixes #107
1 parent 29df081 commit 4154d1f

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

tests/test_ipv6.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55

66

77
@pytest.mark.parametrize(('address',), [
8+
('::',),
89
('::1',),
9-
('dead:beef:0:0:0:0:42:1',),
10+
('1::',),
11+
('dead:beef:0:0:0:0000:42:1',),
1012
('abcd:ef::42:1',),
1113
('0:0:0:0:0:ffff:1.2.3.4',),
1214
('::192.168.30.2',),
@@ -21,6 +23,15 @@ def test_returns_true_on_valid_ipv6_address(address):
2123
('abcd:1234::123::1',),
2224
('1:2:3:4:5:6:7:8:9',),
2325
('abcd::1ffff',),
26+
('1111:',),
27+
(':8888',),
28+
(':1.2.3.4',),
29+
('18:05',),
30+
(':',),
31+
(':1:2:',),
32+
(':1:2::',),
33+
('::1:2::',),
34+
('8::1:2::9',),
2435
])
2536
def test_returns_failed_validation_on_invalid_ipv6_address(address):
2637
assert isinstance(ipv6(address), ValidationFailure)

validators/ip_address.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from operator import xor
2+
13
from .utils import validator
24

35

@@ -57,7 +59,7 @@ def ipv4_cidr(value):
5759
@validator
5860
def ipv6(value):
5961
"""
60-
Return whether or not given value is a valid IP version 6 address
62+
Return whether a given value is a valid IP version 6 address
6163
(including IPv4-mapped IPv6 addresses).
6264
6365
This validator is based on `WTForms IPAddress validator`_.
@@ -112,9 +114,13 @@ def ipv6(value):
112114
if not 0 <= num <= 65536:
113115
return False
114116

115-
if count_blank < 2:
117+
if count_blank == 0 and len(ipv6_groups) == max_groups:
118+
return True
119+
elif count_blank == 1 and ipv6_groups[-1] and ipv6_groups[0]:
120+
return True
121+
elif count_blank == 2 and ((ipv6_groups[0] and not ipv6_groups[-1]) or (not ipv6_groups[0] and ipv6_groups[-1])):
116122
return True
117-
elif count_blank == 2 and not ipv6_groups[0] and not ipv6_groups[1]:
123+
elif count_blank == 3 and len(ipv6_groups) == 3:
118124
return True
119125
return False
120126

0 commit comments

Comments
 (0)