Go/GoLang check IP address in range

前端 未结 5 2000
萌比男神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条回答
  •  死守一世寂寞
    2020-12-29 06:45

    How about some implementation like inet_pton? The result is easy to be stored.

    func IP2Integer(ip *net.IP) (int64, error) {
        ip4 := ip.To4()
        if ip4 == nil {
            return 0, fmt.Errorf("illegal: %v", ip)
        }
    
        bin := make([]string, len(ip4))
        for i, v := range ip4 {
            bin[i] = fmt.Sprintf("%08b", v)
        }
        return strconv.ParseInt(strings.Join(bin, ""), 2, 64)
    }
    

提交回复
热议问题