networking - 如何检测两个 Golang net.IPNet 对象是否相交?

标签 networking go ip ip-address cidr

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

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

Go 是否为这个特定任务提供了实用函数?

请参阅下面的测试代码。

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
}

Go Playground 上运行它

最佳答案

如果(正如您的测试用例所暗示的那样)您不关心哪一侧包含哪一侧,而只是存在重叠,这就足够了。

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

关于networking - 如何检测两个 Golang net.IPNet 对象是否相交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729158/

相关文章:

go - 如何在 grpc-gateway 中进行 302 重定向

dictionary - map接口(interface)指针方法接收者

amazon-web-services - AWS ALB 到 DNS 名称而不是 IP

linux - 浏览器通过ip更改域名,Debian,Apache2

C++获取服务网络状态linux

go - protoc-gen-go-rpc : program not found or is not executable - Where do I get protoc-gen-go-rpc?

蓝牙/bluez5 上的 IP

c++ - 检查 IP 第一个八位字节是否不以 127/224 或 255 开头

networking - 网络掩码、CIDR、网络和 Broadcat IP 地址

python - 如何重现 "Connection reset by peer"