c-robinson / iplib

A library for working with IP addresses and networks in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NextNet seems to return the wrong value

luisdavim opened this issue · comments

See this example:

package main

import (
	"fmt"

	"github.com/c-robinson/iplib"
)

func GetNextSubnet(lastCIDR string, nextSize int) {
	lastNet := iplib.Net4FromStr(lastCIDR)

	if nextSize == 0 {
		nextSize, _ = lastNet.Mask().Size()
	}
	nextNet := lastNet.NextNet(nextSize)
	fmt.Printf("Next net: %s\n", nextNet)
}

func main() {
	GetNextSubnet("10.80.6.0/24", 18)
}

Outputs:

Next net: 10.80.0.0/18

Am I doing something wrong?

If I use the same subnet size, I get an expected result

GetNextSubnet("10.80.6.0/24", 0) // 0 default to the same size

output:

Next net: 10.80.7.0/24

and with:

GetNextSubnet("10.80.6.0/24", 22)

it goes backwards?

Next net: 10.80.4.0/22

Should NextNet do something like this? https://goplay.tools/snippet/a9S9G00guTd

func GetNextSubnet(lastCIDR string, nextSize int) (string, error) {
	lastNet := iplib.Net4FromStr(lastCIDR)

	if nextSize == 0 {
		nextSize, _ = lastNet.Mask().Size()
	}

	// get the last IP on the next net
	nextIP := iplib.IncrementIP4By(iplib.NextIP(lastNet.BroadcastAddress()), uint32(math.Pow(2, 32-float64(nextSize)))-2)
	nextNet := iplib.NewNet4(nextIP, nextSize)

	return nextNet.String(), nil
}

I can open a PR if you agree with this approach.

This looks good, yeah. I'd definitely appreciate the PR