Parse CIDR strings without separating into subnet and address

This commit is contained in:
Bryan Boreham committed 2016-03-02 17:21:52 -08:00
1 parent 73f1a04d5f
commit 604309fb53
3 files changed
+15 -7

No files matched your search

+9 -4
View File
@@ -50,17 +50,22 @@ func ParseIP(s string) (Address, error) {
return 0, &net.ParseError{Type: "IP Address", Text: s}
}
func ParseCIDR(s string) (Address, CIDR, error) {
func ParseCIDR(s string) (CIDR, error) {
if ip, ipnet, err := net.ParseCIDR(s); err != nil {
return 0, CIDR{}, err
return CIDR{}, err
} else if ipnet.IP.To4() == nil {
return 0, CIDR{}, &net.ParseError{Type: "Non-IPv4 address not supported", Text: s}
return CIDR{}, &net.ParseError{Type: "Non-IPv4 address not supported", Text: s}
} else {
prefixLen, _ := ipnet.Mask.Size()
return FromIP4(ip), CIDR{Addr: FromIP4(ipnet.IP), PrefixLen: prefixLen}, nil
return CIDR{Addr: FromIP4(ip), PrefixLen: prefixLen}, nil
}
}
func (cidr CIDR) IsSubnet() bool {
mask := cidr.Size() - 1
return Offset(cidr.Addr)&mask == 0
}
func (cidr CIDR) Size() Offset { return 1 << uint(32-cidr.PrefixLen) }
func (cidr CIDR) Range() Range {