验证IP地址-字符串468-python

python

class Solution:
    def ipv4(self, ip):
        ls = ip.split('.')
        if len(ls) != 4:
            return 'Neither'

        for data in ls:
            if data == '' or (len(data) > 1 and data[0] == '0'):
                return 'Neither'
            try:
                if int(data) < 0 or int(data) > 255:
                    return 'Neither'
            except:
                return 'Neither'
        return 'IPv4'

    def ipv6(self, ip):
        ls = ip.split(':')
        if len(ls) != 8:
            return 'Neither'

        for data in ls:
            if data == '' or len(data) > 4:
                return 'Neither'
            else:
                for j in data:
                    if not j.isdigit() and not 'a' <= j.lower() <= 'f':
                        return 'Neither'
        return 'IPv6'                   
    
    def validIPAddress(self, ip: str):
        if '.' not in ip:
            return self.ipv6(ip)
        else:
            return self.ipv4(ip)

版权声明:本文为VaccyZhu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。