From 8c42ceb8e603151d1132bff24a07e02cf70f1f7d Mon Sep 17 00:00:00 2001 From: Lipu Fei Date: Tue, 30 Apr 2019 07:40:16 +0200 Subject: [PATCH] Use socket to validate IP addresses CURA-6483 --- cura/Utils/networking.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/cura/Utils/networking.py b/cura/Utils/networking.py index ba2bbddff6..0456191cee 100644 --- a/cura/Utils/networking.py +++ b/cura/Utils/networking.py @@ -1,21 +1,27 @@ # Copyright (c) 2019 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. -import re - - -_REGEX_IPV4 = re.compile(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$") -_REGEX_IPV6 = re.compile(r"^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$") +import socket # Checks if the given string is a valid IPv4 address. def isIPv4(address: str) -> bool: - return _REGEX_IPV4.fullmatch(address) is not None + try: + socket.inet_pton(socket.AF_INET, address) + result = True + except: + result = False + return result # Checks if the given string is a valid IPv6 address. def isIPv6(address: str) -> bool: - return _REGEX_IPV6.fullmatch(address) is not None + try: + socket.inet_pton(socket.AF_INET6, address) + result = True + except: + result = False + return result # Checks if the given string is a valid IPv4 or IPv6 address.