douchun3680 2013-11-09 20:53
浏览 1752

Go / GoLang检查IP地址在范围内

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, how would I check if a given input IP address is in that range?

  • 写回答

5条回答 默认 最新

  • dprntkxh703029 2013-11-09 22:42
    关注

    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
    ", trial)
            return false
        }
        if bytes.Compare(trial, ip1) >= 0 && bytes.Compare(trial, ip2) <= 0 {
            fmt.Printf("%v is between %v and %v
    ", trial, ip1, ip2)
            return true
        }
        fmt.Printf("%v is NOT between %v and %v
    ", 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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决