Skip to content

Commit d998737

Browse files
committed
rebaseMe: use socket.inet_pton to validate ip addresses
Signed-off-by: BenjiReis <[email protected]>
1 parent 4b85461 commit d998737

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

XSConsoleUtils.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# with this program; if not, write to the Free Software Foundation, Inc.,
1414
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
1515

16-
import re, signal, string, subprocess, time, types
16+
import re, signal, socket, string, subprocess, time, types
1717
from pprint import pprint
1818

1919
from XSConsoleBases import *
@@ -186,17 +186,31 @@ def DateTimeToSecs(cls, inDateTime):
186186
if retVal <= 3601.0: # Handle the effect of daylight savings on start of epoch
187187
retVal = 0.0
188188
return retVal
189-
189+
190190
class IPUtils:
191+
@classmethod
192+
def ValidateIPFamily(cls, text, family):
193+
try:
194+
socket.inet_pton(family, text)
195+
return True
196+
except socket.error:
197+
return False
198+
199+
@classmethod
200+
def ValidateIPv4(cls, text):
201+
return cls.ValidateIPFamily(text, socket.AF_INET)
202+
203+
@classmethod
204+
def ValidateIPv6(cls, text):
205+
return cls.ValidateIPFamily(text, socket.AF_INET6)
206+
191207
@classmethod
192208
def ValidateIP(cls, text):
193-
ipv4_re = '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}'
194-
ipv6_re = '^(([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]))'
195-
return re.match(ipv4_re, text) or re.match(ipv6_re, text)
196-
209+
return cls.ValidateIPv4(text) or cls.ValidateIPv6(text)
210+
197211
@classmethod
198212
def ValidateNetmask(cls, text):
199-
return cls.ValidateIP(text) or (int(text) > 4 and int(text) < 128)
213+
return cls.ValidateIPv4(text) or (int(text) > 4 and int(text) < 128)
200214

201215
@classmethod
202216
def AssertValidNetmask(cls, inIP):

0 commit comments

Comments
 (0)