# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 验证IP地址 # @param IP string字符串 一个IP地址字符串 # @return string字符串 # class Solution: """ Ipv4 : 1. 十进制和点表示 2.4个十进制数 3.用. 分开 4. 最短 0.0.0.0 len=7 最长 255.255.255.255 len=12+3 Ipv6: 1. 8组用:分开 2.不能出现空组 :: 3.不能出现多余的0 : 0000 4. 每组是16进制数 不能出现A-F a-f 1-9 之外的字符 没有空格或其他字符 测试用例: "2001:0dFG:85a3:0:0:8A2E:0370:7334" G 超出范围 """ def solve(self , IP: str) -> str: # write code here print(IP) def ipv4(IP): if len(IP)<7 or len(IP)>15: return "Neither" ips=IP.split(".") #print(ips) if len(ips)!=4: return "Neither" for it in ips: if it[0]=='0' and len(it)>1: return "Neither" for i in it: print(i) if ord(i)-ord('0')>9: # 不是数字 return "Neither" if int(it)>255: return "Neither" return "IPv4" def ipv6(IP): if "::" in IP: return "Neither" ips=IP.split(":") if len(ips)!=8: return "Neither" for it in ips: if len(it)>4: return "Neither" for ch in it: # 过滤掉不是16进制的 if 'F'<ch<'Z' or 'f'<ch<'z': return "Neither" # print(ips) # for it in ips: # if it[0]=='0' and len(it)>1: # return "Neither" return "IPv6" # if not IP: # return "Neither" if "." in IP: return ipv4(IP) elif ":" in IP: return ipv6(IP) else: return "Neither"