mirror of
https://github.com/Hopiu/linkchecker.git
synced 2026-05-12 08:33:10 +00:00
Use ipaddress in network.iputil.is_valid_ip()
ipaddress was introduced in Python 3.3.
This commit is contained in:
parent
2eb1424703
commit
504004d4f0
1 changed files with 4 additions and 41 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue