CIDR Allowlist IP Check

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

GoSecurity Boundaries

Code

gosnippet
16 lines
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)
}

Inside the snippet

The moving parts are the functions isAllowed and main.

Iteration happens inside for _, cidr := range cidrs — everything outside it runs once. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

Watch out for

  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Putting it to use

The primary signature is func isAllowed(ipStr string, cidrs []string) (bool, error)

Execute the file and main walks through isAllowed, in that order.

Core lines

if ip == nil { return false, fmt.Errorf("invalid IP") }
if err != nil { return false, err }
if network.Contains(ip) { return true, nil }

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As returned `error` values — 1 site in the snippet check `err` before using other results.
How do you run CIDR Allowlist IP Check?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.