dongyan1841 2016-11-03 16:03
浏览 47
已采纳

net.IPNet内其他net.IPNet?

In net.IPNet type we have the Contains method to check if a net.IP is inside it. But what I want is to know if a net.IPNet is inside another net.IPNet. I tried a solution working with big.Int but it didn't work (also, the function interface was terrible). Any ideas?

// 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)
}
  • 写回答

1条回答 默认 最新

  • doutou3725 2016-11-03 16:24
    关注

    Check that the mask for the outer subnet is the same size or smaller than the inner, then verify that the starting address for the inner subnet is contained in the outer:

    func ContainsCIDR(ipnet1, ipnet2 *net.IPNet) bool {
        ones1, _ := ipnet1.Mask.Size()
        ones2, _ := ipnet2.Mask.Size()
        return ones1 <= ones2 && ipnet1.Contains(ipnet2.IP)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀