I do see answers on the stackoverflow for validating the IPs from given string. I am trying to do the same. However, I have a LIST of IPs. I am stuck with the following code. Please help.
I appreciate your time!
def validateIP(self, IP):
def is_IPv4():
i = 0
while i < len(IP):
ls = IP[i].split('.')
if len(ls)== 4 and all( g.isdigit() and (0 >= int(g) < 255) for g in ls):
return True
i += 1
return False
def is_IPv6():
i = 0
while i < len(IP):
ls = IP[i].split('.')
if len(ls) == 8 and all(0 > len(g)< 4 and all( c in '0123456789abcdefABCDE' for c in g) for g in ls):
return True
i += 1
return False
for item in IP:
if '.' in item and is_IPv4():
return 'IPv4'
if ':' in item and is_IPv6():
return 'IPv6'
return 'Neither'
print(validateIP('n', ['100.243.537.591', 'HBA.KJFH.LSHF', '172.16.254.1', '2001:0db8:85a3:0:0:8A2E:0370:7334', '256.256.256.256']))
I didn't recreate your functions, but I put this together for you. The code below can easily be added to a function (e.g. ip_address_validation).
# Python module for Regular expressions
import re
# Valid IPv4 address format
IPv4_format = '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'
# Valid IPv6 address format
IPv6_format = '(([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]))'
possible_IP_addresses = ['100.243.537.591', 'HBA.KJFH.LSHF', '172.16.254.1', '2001:0db8:85a3:0:0:8A2E:0370:7334', '256.256.256.256']
for address in possible_IP_addresses:
is_IPv4 = re.compile(r'{}'.format(IPv4_format))
match_IPv4 = re.match(is_IPv4, address)
is_IPv6 = re.compile(r'{}'.format(IPv6_format))
match_IPv6 = re.match(is_IPv6, address)
if match_IPv4:
print ('Valid IPv4 address: {}'.format(address))
# output
Valid IPv4 address: 172.16.254.1
elif match_IPv6:
print ('Valid IPv6 address: {}'.format(address))
# output
Valid IPv6 address: 2001:0db8:85a3:0:0:8A2E:0370:7334
else:
print ('Not a valid IPv4 or IPv6 address: {}'.format(address))
# output
Not a valid IPv4 or IPv6 address: 100.243.537.591
Not a valid IPv4 or IPv6 address: HBA.KJFH.LSHF
Not a valid IPv4 or IPv6 address: 256.256.256.256