如何检测两个Golang net.IPNet对象是否相交? [英] How to detect if two Golang net.IPNet objects intersect?

查看:396
本文介绍了如何检测两个Golang net.IPNet对象是否相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测两个Golang net.IPNet 对象之间是否存在交集?

How to detect if there is intersection between two Golang net.IPNet objects?

也就是说,如何检查两者,如果第一个网络是第二个网络的子网,或者,如果第二个网络是

That is, how to check both if the first network is subnet of the second one OR if the second network is subnet of the first one.

Go是否提供了可用于此特定任务的实用程序功能?

Does Go provide any utility function ready for this specific task?

查看测试

package main

import (
    "fmt"
    "net"
)

func main() {
    _, net1, _ := net.ParseCIDR("1.1.1.1/24")
    _, net2, _ := net.ParseCIDR("1.1.0.2/16")
    _, net3, _ := net.ParseCIDR("1.1.1.3/25")
    _, net4, _ := net.ParseCIDR("1.2.0.4/16")

    test(net1, net2, true)
    test(net2, net1, true)
    test(net1, net3, true)
    test(net3, net1, true)
    test(net1, net4, false)
    test(net4, net1, false)
}

func test(n1, n2 *net.IPNet, expect bool) {
    result := intersect(n1, n2)
    var label string
    if result == expect {
        label = "good"
    } else {
        label = "FAIL"
    }
    fmt.Printf("test intersect(%v,%v)=%v expected=%v => %s\n", n1, n2, result, expect, label)
}

func intersect(n1, n2 *net.IPNet) bool {
    return false // FIXME WRITEME
}

去游乐场

推荐答案

如果(作为您的测试用例似乎暗示)您不必关心哪一面包含哪一面,而只是存在重叠,就足够了。

If (as your test cases seem to imply) you don't care about which side contains which, but just that there's overlap, this should be sufficient.

func intersect(n1, n2 *net.IPNet) bool {
    return n2.Contains(n1.IP) || n1.Contains(n2.IP)
}

这篇关于如何检测两个Golang net.IPNet对象是否相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆