@@ -23,17 +23,17 @@ def ipv4(value):
23
23
24
24
:param value: IP address string to validate
25
25
"""
26
- parts = value .split ('.' )
27
- if len (parts ) == 4 and all (x .isdigit () for x in parts ):
28
- numbers = list (int (x ) for x in parts )
29
- return all (num >= 0 and num < 256 for num in numbers )
30
- return False
26
+ groups = value .split ('.' )
27
+ if len (groups ) != 4 or any (not x .isdigit () for x in groups ):
28
+ return False
29
+ return all (0 <= int (part ) < 256 for part in groups )
31
30
32
31
33
32
@validator
34
33
def ipv6 (value ):
35
34
"""
36
- Return whether or not given value is a valid IP version 6 address.
35
+ Return whether or not given value is a valid IP version 6 address
36
+ (including IPv4-mapped IPv6 addresses).
37
37
38
38
This validator is based on `WTForms IPAddress validator`_.
39
39
@@ -45,32 +45,48 @@ def ipv6(value):
45
45
>>> ipv6('abcd:ef::42:1')
46
46
True
47
47
48
+ >>> ipv6('::ffff:192.0.2.128')
49
+ True
50
+
51
+ >>> ipv6('::192.0.2.128')
52
+ True
53
+
48
54
>>> ipv6('abc.0.0.1')
49
55
ValidationFailure(func=ipv6, args={'value': 'abc.0.0.1'})
50
56
51
57
.. versionadded:: 0.2
52
58
53
59
:param value: IP address string to validate
54
60
"""
55
- parts = value .split (':' )
56
- if len (parts ) > 8 :
61
+ ipv6_groups = value .split (':' )
62
+ ipv4_groups = ipv6_groups [- 1 ].split ('.' )
63
+
64
+ if len (ipv4_groups ) > 1 :
65
+ if not ipv4 (ipv6_groups [- 1 ]):
66
+ return False
67
+ ipv6_groups = ipv6_groups [:- 1 ]
68
+ else :
69
+ ipv4_groups = []
70
+
71
+ max_groups = 6 if ipv4_groups else 8
72
+ if len (ipv6_groups ) > max_groups :
57
73
return False
58
74
59
- num_blank = 0
60
- for part in parts :
75
+ count_blank = 0
76
+ for part in ipv6_groups :
61
77
if not part :
62
- num_blank += 1
78
+ count_blank += 1
79
+ continue
80
+ try :
81
+ num = int (part , 16 )
82
+ except ValueError :
83
+ return False
63
84
else :
64
- try :
65
- value = int (part , 16 )
66
- except ValueError :
85
+ if not 0 <= num <= 65536 :
67
86
return False
68
- else :
69
- if value < 0 or value >= 65536 :
70
- return False
71
87
72
- if num_blank < 2 :
88
+ if count_blank < 2 :
73
89
return True
74
- elif num_blank == 2 and not parts [0 ] and not parts [1 ]:
90
+ elif count_blank == 2 and not ipv6_groups [0 ] and not ipv6_groups [1 ]:
75
91
return True
76
92
return False
0 commit comments