把 /24 切成四个 /26
(每道题开头都有同一段:to_int 把点分十进制变成 32 位整数,to_str 变回去,mask(前缀长度) 给出掩码的整数——高位连续的 1,低位 0。)
split 把一个网按新前缀切开:起点是网络地址,每个子网跨 2 的(32 − 新前缀)次方个地址。看四个子网的网络地址:
def to_int(ip):
a, b, c, d = [int(x) for x in ip.split(".")]
return (a << 24) | (b << 16) | (c << 8) | d
def to_str(n):
return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))
def mask(prefix):
return (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
def split(net, prefix, new_prefix):
base = to_int(net) & mask(prefix)
step = 2 ** (32 - new_prefix)
return [to_str(base + i * step) for i in range(2 ** (new_prefix - prefix))]
print(",".join(split("192.168.10.0", 24, 26)))
全部评论