登录
首页 >  Golang >  Go问答

在 golang 上的大型 ip/子网列表中搜索 ip 的最快方法?

来源:stackoverflow

时间:2024-04-16 17:06:31 336浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 golang 上的大型 ip/子网列表中搜索 ip 的最快方法?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

请帮我以最快的方式解决下一个任务

我有一个很大的 ip/子网列表,例如...

35.132.199.128/27
8.44.144.248/32
87.117.185.193
45.23.45.45

等 我需要在 go 中尽可能在该列表中找到一些 ip。

当我尝试使用字符串切片和范围时,在大型列表上速度非常慢。

我可以使用地图吗,比如map[string]string,它看起来可用,但只能用于ip检查,不能用于子网检查。

谁能帮我解决这个任务?谢谢。

我的代码

func (app *application) validateIP(ip string) bool {

for _, item := range app.IPList {

    itemIsIP := net.ParseIP(item)

    if itemIsIP != nil {
        if ip == itemIsIP.String() {
            return true
        }
        continue
    }

    _, itemNet, err := net.ParseCIDR(item)
    if err != nil {
        log.Printf("[ERROR] %+v", err)
    }

    checkedIP := net.ParseIP(ip)

    if itemNet.Contains(checkedIP) {
        return true
    }
}
return false

}


解决方案


trie 是一种用于快速包含搜索地址和 cidr 地址块的理想数据结构。 以下代码展示了如何使用ipaddress-go library 解决 trie 实现以进行快速包含搜索。免责声明:我是 ipaddress 库的项目经理。

package main

import (
    "fmt"
    "github.com/seancfoley/ipaddress-go/ipaddr"
)

func main() {
    addrstrs := []string{
        "35.132.199.128/27", "8.44.144.248/32", "87.117.185.193", "45.23.45.45",
    }
    trie := ipaddr.addresstrie{}
    for _, addrstr := range addrstrs {
        addr := ipaddr.newipaddressstring(addrstr).getaddress().toaddressbase()
        trie.add(addr)
    }
    fmt.println("the trie is", trie)

    addrsearchstrs := []string{
        "35.132.199.143", "8.44.144.248", "45.23.45.45", "127.0.0.1",
    }
    for _, addrstr := range addrsearchstrs {
        addr := ipaddr.newipaddressstring(addrstr).getaddress().toaddressbase()
        triepath := trie.elementscontaining(addr)
        if triepath.count() > 0 {
            fmt.println("the blocks and addresses containing", addr, "are",
            triepath)
        } else {
            fmt.println("no blocks nor addresses contain", addr)
        }
    }
}

输出:

The trie is 
○ 0.0.0.0/0 (4)
└─○ 0.0.0.0/1 (4)
  ├─○ 0.0.0.0/2 (3)
  │ ├─● 8.44.144.248 (1)
  │ └─○ 32.0.0.0/4 (2)
  │   ├─● 35.132.199.128/27 (1)
  │   └─● 45.23.45.45 (1)
  └─● 87.117.185.193 (1)

The blocks and addresses containing 35.132.199.143 are 
● 35.132.199.128/27 (1)

The blocks and addresses containing 8.44.144.248 are 
● 8.44.144.248 (1)

The blocks and addresses containing 45.23.45.45 are 
● 45.23.45.45 (1)

No blocks nor addresses contain 127.0.0.1

好了,本文到此结束,带大家了解了《在 golang 上的大型 ip/子网列表中搜索 ip 的最快方法?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>