Skip to content

Commit

Permalink
feat: add a function to format IPs in CIDR notation
Browse files Browse the repository at this point in the history
This is frequently used in Talos.

Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com>
  • Loading branch information
smira authored and talos-bot committed Feb 4, 2021
1 parent 005a94f commit 52c7509
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions net.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ func FormatAddress(addr string) string {
return addr
}

// FormatCIDR formats IP from the network as CIDR notation.
func FormatCIDR(ip net.IP, network net.IPNet) string {
ones, _ := network.Mask.Size()

return fmt.Sprintf("%s/%d", ip, ones)
}

// AddressContainsPort checks to see if the supplied address contains both an address and a port.
// This will not catch every possible permutation, but it is a best-effort routine suitable for prechecking human-interactive parameters.
func AddressContainsPort(addr string) bool {
Expand Down
11 changes: 11 additions & 0 deletions net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ func TestFormatAddress(t *testing.T) {
assert.Equal(t, talosnet.FormatAddress("alpha.beta.gamma.com"), "alpha.beta.gamma.com")
}

func TestFormatCIDR(t *testing.T) {
ip4 := net.ParseIP("192.168.1.1")
_, cidr4, _ := net.ParseCIDR("192.168.0.0/16") //nolint: errcheck

ip6 := net.ParseIP("2001:db8::1")
_, cidr6, _ := net.ParseCIDR("2001:db8::/32") //nolint: errcheck

assert.Equal(t, talosnet.FormatCIDR(ip4, *cidr4), "192.168.1.1/16")
assert.Equal(t, talosnet.FormatCIDR(ip6, *cidr6), "2001:db8::1/32")
}

//nolint: scopelint
func TestNthIPInNetwork(t *testing.T) {
type args struct {
Expand Down

0 comments on commit 52c7509

Please sign in to comment.