Skip to content

Commit

Permalink
lang: core: net: Add new function to get cidr prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
purpleidea committed Nov 7, 2024
1 parent 69e84fb commit c642b5e
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lang/core/net/cidr_to_ip_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ package corenet
import (
"context"
"net"
"strconv"
"strings"

"github.com/purpleidea/mgmt/lang/funcs/simple"
Expand All @@ -43,6 +44,10 @@ func init() {
T: types.NewType("func(a str) str"),
F: CidrToIP,
})
simple.ModuleRegister(ModuleName, "cidr_to_prefix", &simple.Scaffold{
T: types.NewType("func(a str) str"),
F: CidrToPrefix,
})
simple.ModuleRegister(ModuleName, "cidr_to_mask", &simple.Scaffold{
T: types.NewType("func(a str) str"),
F: CidrToMask,
Expand All @@ -61,6 +66,22 @@ func CidrToIP(ctx context.Context, input []types.Value) (types.Value, error) {
}, nil
}

// CidrToPrefix returns the prefix from a CIDR address. For example, if you give
// us 192.0.2.0/24 then we will return "24" as a string.
func CidrToPrefix(ctx context.Context, input []types.Value) (types.Value, error) {
cidr := input[0].Str()
_, ipnet, err := net.ParseCIDR(strings.TrimSpace(cidr))
if err != nil {
return nil, err
}

ones, _ := ipnet.Mask.Size()

return &types.StrValue{
V: strconv.Itoa(ones),
}, nil
}

// CidrToMask returns the subnet mask from a CIDR address.
func CidrToMask(ctx context.Context, input []types.Value) (types.Value, error) {
cidr := input[0].Str()
Expand Down

0 comments on commit c642b5e

Please sign in to comment.