net.IPNet 内其他 net.IPNet?

net.IPNet inside other net.IPNet?

net.IPNet 类型中,我们有 Contains 方法来检查其中是否有 net.IP。但我想知道 net.IPNet 是否在另一个 net.IPNet 中。我尝试了一个使用 big.Int 的解决方案,但它没有用(而且,函数接口很糟糕)。有什么想法吗?

// ipnet2 contains ipnet1 ?
func ContainsCIDR(ipnet1, ipnet2 net.IPNet) bool {
    var begin big.Int
    begin.SetBytes([]byte(ipnet1.IP))

    var mask big.Int
    mask.SetBytes([]byte(ipnet1.Mask))

    var diff big.Int
    diff.Xor(&begin, &mask)

    var end big.Int
    end.Add(&begin, &diff)

    ipBegin := net.IP(begin.Bytes())
    ipEnd := net.IP(end.Bytes())

    return ipnet2.Contains(ipBegin) && ipnet2.Contains(ipEnd)
}

检查外部子网的掩码大小是否等于或小于内部子网,然后验证内部子网的起始地址是否包含在外部:

func ContainsCIDR(ipnet1, ipnet2 *net.IPNet) bool {
    ones1, _ := ipnet1.Mask.Size()
    ones2, _ := ipnet2.Mask.Size()
    return ones1 <= ones2 && ipnet1.Contains(ipnet2.IP)
}