Skip to content

Commit 09bd22d

Browse files
committed
Validate IP addresses using the ipaddress module.
1 parent 4e7870b commit 09bd22d

File tree

1 file changed

+12
-19
lines changed

1 file changed

+12
-19
lines changed

jsonschema/_format.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import datetime
2+
import ipaddress
23
import re
3-
import socket
4-
import struct
54

65
from jsonschema.exceptions import FormatError
76

@@ -183,30 +182,24 @@ def is_email(instance):
183182
return "@" in instance
184183

185184

186-
_ipv4_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
187-
188-
189185
@_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,
191191
)
192192
def is_ipv4(instance):
193193
if not isinstance(instance, str):
194194
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)
198196

199197

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)
210203

211204

212205
try:

0 commit comments

Comments
 (0)