题解 | 验证IP地址

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
    def solve(self , IP: str) -> str:
        # write code here
        if IP.count(".") == 3:
            _list = IP.split(".")
            if len(_list) == 4:
                for i in _list:
                    if not i.isdigit(): 
                        return "Neither"
                    if i != str(int(i)): 
                        return "Neither"
                    if int(i) > 255 or int(i) < 0: 
                        return "Neither"
                return "IPv4"
            else:
                return "Neither"
        elif IP.count(":") == 7:
            _list = IP.split(":")
            if len(_list) == 8:
                for i in _list:
                    try:
                        value = int('0x'+ i, 16)
                    except ValueError:
                        return "Neither" 
                    if value < 0 or value > 0xffff or len(i) > 4:
                        return "Neither"
                return "IPv6"
            else:
                return "Neither"
        else:
            return "Neither"

全部评论

相关推荐

天门一键开:她的意思是问你有没有论文吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务