Skip to content

Instantly share code, notes, and snippets.

@peacefixation
Last active March 27, 2019 01:33
Show Gist options
  • Save peacefixation/9ca4bde3beb5e9a2c1e7bac0c0ff7bfd to your computer and use it in GitHub Desktop.
Save peacefixation/9ca4bde3beb5e9a2c1e7bac0c0ff7bfd to your computer and use it in GitHub Desktop.
Subnet contains IP
// SubnetContainsIP check if an IP address is part of the subnet given by the CIDR (ie. '192.168.0.0/24')
func SubnetContainsIP(CIDR, addr string) (bool, error) {
_, ipNet, err := net.ParseCIDR(CIDR)
if err != nil {
return false, fmt.Errorf("Error parsing CIDR '%s'", CIDR)
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false, fmt.Errorf("Error parsing address '%s'. %v", addr, err)
}
ip := net.ParseIP(host)
if ip == nil {
return false, fmt.Errorf("Error parsing host '%s' from address '%s'", host, addr)
}
return ipNet.Contains(ip), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment