对0位压缩的 ipv6,进行补全
import socket,struct ipv6 = "FF01::FF01:FF01" 前64位 = hex(struct.unpack("!Q",socket.inet_pton(socket.AF_INET6,ipv6)[:8])[0])[2:] 后64位 = hex(struct.unpack("!Q",socket.inet_pton(socket.AF_INET6,ipv6)[8:])[0])[2:]
l = [ # "ABCD:EF01:2345:6789:DCAB:DD01:5623:1298", # "2001:DB8:0:23:8:800:200C:417A", # "::DB8:0:23:8:800:200C:417A", # "::DB8:23:8:800:200C:417A", # "::1:ABC:2", # "::1", # "1::2", # "FF01:ABCD::1101", # "2001:DB8::23:8:800:200C:417A", "DB8:0:23:8:800:200C:417A::", "1:2::", "1::", ] for ip in l: if "::" not in ip: # 没有0位压缩 l1 = ip.split(":") elif "::" in ip: # 0位压缩 l1 = ip.split(":") if len(l1) > 8: # 只压缩一个0,在前面或后面 if l1[0] == "": l1.pop(0) elif l1[-1] == "": l1.pop(-1) for index,value in enumerate(l1): if value == "": l1[index] = str(0) elif len(l1) == 8: # 压缩一个0,在中间 for index,value in enumerate(l1): if value == "": l1[index] = str(0) elif len(l1) < 8: # 压缩多个0 s = "0" n = 8 - len(l1) for index,value in enumerate(l1): if value == "": l1[index] = str(0) for i in range(n): l1.insert(index,"0") print(ip) # print(l1) print("==前64==",":".join(l1[:4])) print("==后64==",":".join(l1[-4:]))