aboutsummaryrefslogtreecommitdiff
path: root/ipmask.go
diff options
context:
space:
mode:
Diffstat (limited to 'ipmask.go')
-rw-r--r--ipmask.go38
1 files changed, 37 insertions, 1 deletions
diff --git a/ipmask.go b/ipmask.go
index 09b9533..1b10efb 100644
--- a/ipmask.go
+++ b/ipmask.go
@@ -3,6 +3,7 @@ package pflag
import (
"fmt"
"net"
+ "strconv"
)
// -- net.IPMask value
@@ -32,11 +33,46 @@ func (i *ipMaskValue) Type() string {
func ParseIPv4Mask(s string) net.IPMask {
mask := net.ParseIP(s)
if mask == nil {
- return nil
+ if len(s) != 8 {
+ return nil
+ }
+ // net.IPMask.String() actually outputs things like ffffff00
+ // so write a horrible parser for that as well :-(
+ m := []int{}
+ for i := 0; i < 4; i++ {
+ b := "0x" + s[2*i:2*i+2]
+ d, err := strconv.ParseInt(b, 0, 0)
+ if err != nil {
+ return nil
+ }
+ m = append(m, int(d))
+ }
+ s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
+ mask = net.ParseIP(s)
+ if mask == nil {
+ return nil
+ }
}
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}
+func parseIPv4Mask(sval string) (interface{}, error) {
+ mask := ParseIPv4Mask(sval)
+ if mask == nil {
+ return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval)
+ }
+ return mask, nil
+}
+
+// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name
+func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) {
+ val, err := f.getFlagType(name, "ipMask", parseIPv4Mask)
+ if err != nil {
+ return nil, err
+ }
+ return val.(net.IPMask), nil
+}
+
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.
func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {