从Python中的给定列表中验证IP地址

时间:2019-02-14 20:32:44

标签: python-3.x validation ip-address

我确实在stackoverflow上看到了从给定字符串验证IP的答案。我正在尝试做同样的事情。但是,我有一个IP列表。 我坚持下面的代码。请帮忙。

感谢您的宝贵时间!

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']))

1 个答案:

答案 0 :(得分:1)

我没有重新创建您的函数,但是我为您合并了这些函数。下面的代码可以轻松地添加到函数中(例如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