美文网首页
golang检测ip地址是否在某个区间

golang检测ip地址是否在某个区间

作者: louhangfei | 来源:发表于2019-06-28 15:13 被阅读0次

    IP地址表示为bigendian []byte 在去的切片( IP type)所以将正确比较使用 bytes.Compare

    例如

    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")
    }
    

    参考http://landcareweb.com/questions/27269/go-golangjian-cha-fan-wei-nei-de-ipdi-zhi

    相关文章

      网友评论

          本文标题:golang检测ip地址是否在某个区间

          本文链接:https://www.haomeiwen.com/subject/yfzjcctx.html