From 504004d4f09b609d119b0e531fb73a8612566eb3 Mon Sep 17 00:00:00 2001 From: Chris Mayo Date: Tue, 31 Mar 2020 19:46:31 +0100 Subject: [PATCH] Use ipaddress in network.iputil.is_valid_ip() ipaddress was introduced in Python 3.3. --- linkcheck/network/iputil.py | 45 ++++--------------------------------- 1 file changed, 4 insertions(+), 41 deletions(-) diff --git a/linkcheck/network/iputil.py b/linkcheck/network/iputil.py index c6c7c965..ef7b6e02 100644 --- a/linkcheck/network/iputil.py +++ b/linkcheck/network/iputil.py @@ -18,55 +18,18 @@ Ip number related utility functions. """ +import ipaddress import re import socket from .. import log, LOG_CHECK - -# IP Adress regular expressions -# Note that each IPv4 octet can be encoded in dezimal, hexadezimal and octal. -_ipv4_num = r"\d{1,3}" -# XXX -_ipv4_num_4 = r"%s\.%s\.%s\.%s" % ((_ipv4_num,) * 4) -_ipv4_re = re.compile(r"^%s$" % _ipv4_num_4) - - -# IPv6; See also rfc2373 -_ipv6_num = r"[\da-f]{1,4}" -_ipv6_re = re.compile(r"^%s:%s:%s:%s:%s:%s:%s:%s$" % ((_ipv6_num,) * 8)) -_ipv6_ipv4_re = re.compile(r"^%s:%s:%s:%s:%s:%s:" % ((_ipv6_num,) * 6) + \ - r"%s$" % _ipv4_num_4) -_ipv6_abbr_re = re.compile(r"^((%s:){0,6}%s)?::((%s:){0,6}%s)?$" % \ - ((_ipv6_num,) * 4)) -_ipv6_ipv4_abbr_re = re.compile(r"^((%s:){0,4}%s)?::((%s:){0,5})?" % \ - ((_ipv6_num,) * 3) + \ - "%s$" % _ipv4_num_4) - - def is_valid_ip (ip): """ Return True if given ip is a valid IPv4 or IPv6 address. """ - return is_valid_ipv4(ip) or is_valid_ipv6(ip) - - -def is_valid_ipv4 (ip): - """ - Return True if given ip is a valid IPv4 address. - """ - if not _ipv4_re.match(ip): - return False - a, b, c, d = [int(i) for i in ip.split(".")] - return a <= 255 and b <= 255 and c <= 255 and d <= 255 - - -def is_valid_ipv6 (ip): - """ - Return True if given ip is a valid IPv6 address. - """ - # XXX this is not complete: check ipv6 and ipv4 semantics too here - if not (_ipv6_re.match(ip) or _ipv6_ipv4_re.match(ip) or - _ipv6_abbr_re.match(ip) or _ipv6_ipv4_abbr_re.match(ip)): + try: + ipaddress.ip_address(ip) + except ValueError: return False return True