Last active
March 27, 2019 01:33
-
-
Save peacefixation/9ca4bde3beb5e9a2c1e7bac0c0ff7bfd to your computer and use it in GitHub Desktop.
Subnet contains IP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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