Skip to content

Commit 8b714c3

Browse files
committed
Improve IPv6 validation
fixes #107
1 parent 29df081 commit 8b714c3

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
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: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
@validator
55
def ipv4(value):
66
"""
7-
Return whether or not given value is a valid IP version 4 address.
7+
Return whether a given value is a valid IP version 4 address.
88
99
This validator is based on `WTForms IPAddress validator`_
1010
@@ -32,7 +32,7 @@ def ipv4(value):
3232
@validator
3333
def ipv4_cidr(value):
3434
"""
35-
Return whether or not given value is a valid CIDR-notated IP version 4
35+
Return whether a given value is a valid CIDR-notated IP version 4
3636
address range.
3737
3838
This validator is based on RFC4632 3.1.
@@ -57,7 +57,7 @@ def ipv4_cidr(value):
5757
@validator
5858
def ipv6(value):
5959
"""
60-
Return whether or not given value is a valid IP version 6 address
60+
Return whether a given value is a valid IP version 6 address
6161
(including IPv4-mapped IPv6 addresses).
6262
6363
This validator is based on `WTForms IPAddress validator`_.
@@ -112,17 +112,21 @@ def ipv6(value):
112112
if not 0 <= num <= 65536:
113113
return False
114114

115-
if count_blank < 2:
115+
if count_blank == 0 and len(ipv6_groups) == max_groups:
116116
return True
117-
elif count_blank == 2 and not ipv6_groups[0] and not ipv6_groups[1]:
117+
elif count_blank == 1 and ipv6_groups[-1] and ipv6_groups[0]:
118+
return True
119+
elif count_blank == 2 and ((ipv6_groups[0] and not ipv6_groups[-1]) or (not ipv6_groups[0] and ipv6_groups[-1])):
120+
return True
121+
elif count_blank == 3 and len(ipv6_groups) == 3:
118122
return True
119123
return False
120124

121125

122126
@validator
123127
def ipv6_cidr(value):
124128
"""
125-
Returns whether or not given value is a valid CIDR-notated IP version 6
129+
Returns whether a given value is a valid CIDR-notated IP version 6
126130
address range.
127131
128132
This validator is based on RFC4632 3.1.

0 commit comments

Comments
 (0)