util/net/cidr/range.go

45 lines
962 B
Go
Raw Normal View History

2017-11-17 10:07:00 +00:00
package cidr
import (
"fmt"
"net"
)
func NewCIDRRanger(cidr string) (CIDRRanger, error) {
2017-11-17 10:34:21 +00:00
_, nIPNet, err := net.ParseCIDR(cidr)
2017-11-17 10:07:00 +00:00
if nil != err {
return nil, err
}
2017-11-17 10:34:21 +00:00
switch len(nIPNet.IP) {
2017-11-17 10:07:00 +00:00
case net.IPv4len:
cr := &cidrRangeIPv4{
cidrNet: nIPNet,
}
return cr, nil
case net.IPv6len:
cr := &cidrRangeIPv6{
cidrNet: nIPNet,
}
return cr, nil
default:
return nil, fmt.Errorf("Net: not supported IP length")
}
}
type CIDRRanger interface {
Contains(ip net.IP) bool
First() net.IP
Last() net.IP
2017-11-22 05:52:17 +00:00
Range() []net.IP
2017-11-22 06:07:33 +00:00
// (!Contains(startIP) || !Contains(endIP)) return error
// (startIP > endIP) return error
2017-11-22 05:52:17 +00:00
// (nil != startIP && nil != endIP) return (startIP ~ endIP) + include - exclude
// (nil == startIP || nil == endIP) return include - exclude
2017-11-22 06:07:33 +00:00
Ranges(startIP net.IP, endIP net.IP, include []net.IP, exclude []net.IP) ([]net.IP, error)
2017-11-17 10:07:00 +00:00
Broadcast() net.IP
Network() net.IP
2017-11-17 10:12:50 +00:00
Next(ip net.IP) net.IP
Previous(ip net.IP) net.IP
2017-11-17 10:07:00 +00:00
}