Go/GoLang check IP address in range

前端 未结 5 2009
萌比男神i
萌比男神i 2020-12-29 06:12

In Go/GoLang, what is the fastest way to check if an IP address is in a specific range?

For example, given range 216.14.49.184 to 216.14.49.191

5条回答
  •  猫巷女王i
    2020-12-29 06:48

    IP addresses are represented as bigendian []byte slices in go (the IP type) so will compare correctly using bytes.Compare.

    Eg (play)

    package main
    
    import (
        "bytes"
        "fmt"
        "net"
    )
    
    var (
        ip1 = net.ParseIP("216.14.49.184")
        ip2 = net.ParseIP("216.14.49.191")
    )
    
    func check(ip string) bool {
        trial := net.ParseIP(ip)
        if trial.To4() == nil {
            fmt.Printf("%v is not an IPv4 address\n", trial)
            return false
        }
        if bytes.Compare(trial, ip1) >= 0 && bytes.Compare(trial, ip2) <= 0 {
            fmt.Printf("%v is between %v and %v\n", trial, ip1, ip2)
            return true
        }
        fmt.Printf("%v is NOT between %v and %v\n", trial, ip1, ip2)
        return false
    }
    
    func main() {
        check("1.2.3.4")
        check("216.14.49.185")
        check("1::16")
    }
    

    Which produces

    1.2.3.4 is NOT between 216.14.49.184 and 216.14.49.191
    216.14.49.185 is between 216.14.49.184 and 216.14.49.191
    1::16 is not an IPv4 address
    

提交回复
热议问题