Go/GoLang check IP address in range

前端 未结 5 2018
萌比男神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:48

    This is already in the stdlib in the "net" package as a function called net.Contains. You dont need to rewrite code that already exists!

    See documentation here.

    To use it you just have to parse the desired subnets

    network := "192.168.5.0/24"
    clientips := []string{
        "192.168.5.1",
        "192.168.6.0",
    }
    _, subnet, _ := net.ParseCIDR(network)
    for _, clientip := range clientips {
        ip := net.ParseIP(clientip)
        if subnet.Contains(ip) {
            fmt.Println("IP in subnet", clientip)
        }
    }
    

    In case the above code doesn't make sense here is a google play link

提交回复
热议问题