验证字符串是否是有效的 IPv4 或 IPv6 地址

IPv4 地址:

    每个地址包含4个十进制数 范围为 0 - 255 用(“.”)分割。比如,172.16.254.1 IPv4 地址内的数不会以 0 开头

IPv6 地址:由8组16进制的数字来表示,每组表示 16 比特

    这些组数字通过 (“:”)分割 比如 :2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址 可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写 比如:2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 不能因为某个组的值为 0,而使用一个空的组,以至于出现 ( :: ) 的情况 比如:2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址 多余的 0 也是不被允许的 比如:02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的
class Solution:
    def solve(self, IP: str) -> str:
        # write code here
        items = []
        if len(IP) == 0:
            return "Neither"
        for i in range(len(IP)):
            if IP[i] == ".":
                items = IP.split(".")
                for key in items:
                    if key.isdigit():
                        if 0 <= int(key) <= 255:
                            for s in key:
                                if s == "0":
                                    return "Neither"
                        else:
                            return "Neither"
                    else:
                        return "Neither"
                return "IPv4"
            elif IP[i] == ":":
                items = IP.split(":")
                for item in items:
                    if item == "" or len(item) > 4:
                        return "Neither"
                    for key in item:
                        if key.isalpha():
                           if key not in("A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f"):
                               return "Neither"
                return "IPv6"
经验分享 程序员 微信小程序 职场和发展