简体   繁体   中英

Translation of CIDR block to net.IP type

I have this piece of code:

// redacted 
var (
        cidr        net.IPNet   
        createCmd   = &cobra.Command{
            Use:   "create",
            Short: "create would create something useful",
            Long:  "create submits a request for something useful creation based on parameters provided ",
            Run: func(cmd *cobra.Command, args []string) {
                //region comes from rootCmd

                log.Infof("cidr: %v, ipmask: %v", cidr, cidr.IP.DefaultMask())

            },
        }
    )

func init() {

    createCmd.Flags().IPNetVar(&cidr, "vpc-cidr", cidr, "Vpc cidr range")

}

// redacted

Ouput:

./somethinguseful create --cidr 192.168.100.0/24
INFO[0000] cidr: {192.168.100.0 ffffff00}, ipmask: ffffff00

I am unable to comprehend at what stage does the command line argument 192.168.100.0/24 gets converted into an net.IP and Mask.

Looking at IPNet code

func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
    *p = val
    return (*ipNetValue)(p) 
}
// allocates default to pointer to net.IPNet if provided

There is no piece of code that translates input to the displayed output. How is the mask value calculated and printed out based on input which is cidr block. Any pointers please.

Well, this is being used at the root as a flag, and flags require the flag.Value interface. And all that interface requires is that it is a Stringer and that it implements Set(string) error .

ipNetValue does exactly that

func (ipnet ipNetValue) String() string {
    n := net.IPNet(ipnet)
    return n.String()
}

func (ipnet *ipNetValue) Set(value string) error {
    _, n, err := net.ParseCIDR(strings.TrimSpace(value))
    if err != nil {
        return err
    }
    *ipnet = ipNetValue(*n)
    return nil
}

That leads us to https://golang.org/pkg/net/#ParseCIDR .

Source: https://golang.org/src/net/ip.go?s=16363:16407#L699

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM