CIDR Allowlist IP Check

Check if an IP address is within allowed CIDR ranges for network access control.

GoSecurity Boundaries

Code

snippet
package main
import ("net";"fmt")
func isAllowed(ipStr string, cidrs []string) (bool, error) {
    ip := net.ParseIP(ipStr)
    if ip == nil { return false, fmt.Errorf("invalid IP") }
    for _, cidr := range cidrs {
        _, network, err := net.ParseCIDR(cidr)
        if err != nil { return false, err }
        if network.Contains(ip) { return true, nil }
    }
    return false, nil
}
func main() {
    allowed, _ := isAllowed("10.0.0.5", []string{"10.0.0.0/8", "192.168.0.0/16"})
    fmt.Println(allowed)
}