CIDR Allowlist IP Check
Check if an IP address is within allowed CIDR ranges for network access control.
Code
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
errcheck 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
CIDR to IP ListExpand an IPv4 CIDR block into its individual addresses, showing network, broadcast, total count, and a bounded list you can copy.IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.