Efficient way to check IP in slice of IP addresses in Golang

后端 未结 2 1456
旧时难觅i
旧时难觅i 2021-01-25 17:13

I\'m developing a network application in Golang. I have a slice of IP addresses. Each time a request comes I use net.LookupIP(host) to find out IP address of host w

2条回答
  •  没有蜡笔的小新
    2021-01-25 17:24

    You may use func (ip IP) Equal(x IP) bool from net package:

    Equal reports whether ip and x are the same IP address. An IPv4 address and that same address in IPv6 form are considered to be equal.

    Like this working sample:

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        ip := net.ParseIP("127.0.0.1")
        ips, err := net.LookupIP("localhost")
        if err != nil {
            panic(err)
        }
        for _, v := range ips {
            if v.Equal(ip) {
                fmt.Println(v)
            }
        }
    }
    

提交回复
热议问题