|
1 | 1 | import datetime
|
| 2 | +import ipaddress |
2 | 3 | import re
|
3 |
| -import socket |
4 |
| -import struct |
5 | 4 |
|
6 | 5 | from jsonschema.exceptions import FormatError
|
7 | 6 |
|
@@ -183,30 +182,24 @@ def is_email(instance):
|
183 | 182 | return "@" in instance
|
184 | 183 |
|
185 | 184 |
|
186 |
| -_ipv4_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") |
187 |
| - |
188 |
| - |
189 | 185 | @_checks_drafts(
|
190 |
| - draft3="ip-address", draft4="ipv4", draft6="ipv4", draft7="ipv4", |
| 186 | + draft3="ip-address", |
| 187 | + draft4="ipv4", |
| 188 | + draft6="ipv4", |
| 189 | + draft7="ipv4", |
| 190 | + raises=ipaddress.AddressValueError, |
191 | 191 | )
|
192 | 192 | def is_ipv4(instance):
|
193 | 193 | if not isinstance(instance, str):
|
194 | 194 | return True
|
195 |
| - if not _ipv4_re.match(instance): |
196 |
| - return False |
197 |
| - return all(0 <= int(component) <= 255 for component in instance.split(".")) |
| 195 | + return ipaddress.IPv4Address(instance) |
198 | 196 |
|
199 | 197 |
|
200 |
| -if hasattr(socket, "inet_pton"): |
201 |
| - # FIXME: Really this only should raise struct.error, but see the sadness |
202 |
| - # that is https://twistedmatrix.com/trac/ticket/9409 |
203 |
| - @_checks_drafts( |
204 |
| - name="ipv6", raises=(socket.error, struct.error, ValueError), |
205 |
| - ) |
206 |
| - def is_ipv6(instance): |
207 |
| - if not isinstance(instance, str): |
208 |
| - return True |
209 |
| - return socket.inet_pton(socket.AF_INET6, instance) |
| 198 | +@_checks_drafts(name="ipv6", raises=ipaddress.AddressValueError) |
| 199 | +def is_ipv6(instance): |
| 200 | + if not isinstance(instance, str): |
| 201 | + return True |
| 202 | + return ipaddress.IPv6Address(instance) |
210 | 203 |
|
211 | 204 |
|
212 | 205 | try:
|
|
0 commit comments