Closed micruzz82 closed 2 years ago
The following code works identically and produces identical output to your python code, except for the fact I am hard-coding the command-line args rather than using go's "flags" package:
package main
import (
"fmt"
"github.com/seancfoley/ipaddress-go/ipaddr"
)
func main() {
taken := []*ipaddr.IPAddress{addr("10.255.255.192/26"), addr("10.255.255.128/30")}
main := addr("10.255.255.0/24")
available := get_available_subnets(main, taken)
fmt.Println("\nAvailable IP space:")
for _, avl := range available {
fmt.Println(avl)
}
}
func get_available_subnets(mainSubnet *ipaddr.IPAddress, taken []*ipaddr.IPAddress) []*ipaddr.IPAddress {
var available, q []*ipaddr.IPAddress
q = append(q, mainSubnet)
matched := false
for len(q) > 0 {
subnet := q[0]
q = q[1:]
for _, taken_subnet := range taken {
if matched = subnet.Equal(taken_subnet); matched {
// found matching subnet in taken, stop expanding
fmt.Printf("similar: %s and %s\n", subnet, taken_subnet)
break
}
if matched = subnet.Contains(taken_subnet); matched {
// still has overlaps somewhere in children, keep expanding
fmt.Printf("overlaps: %s and %s\n", subnet, taken_subnet)
iter := subnet.AdjustPrefixLen(1).PrefixBlockIterator()
for iter.HasNext() {
sub_subnet := iter.Next()
q = append(q, sub_subnet)
}
break
}
}
if !matched {
// no overlaps with taken - this subnet is entirely available
available = append(available, subnet)
}
}
return available
}
func addr(addrStr string) *ipaddr.IPAddress {
return ipaddr.NewIPAddressString(addrStr).GetAddress()
}
Hi Sean
I just wanted to present another idea I was looking into which was to find out all the remaining IP space available, if IP allocation was randomly done. This code uses breadth first search and is able to provide the information required. If this is also possible with ipaddress-go then it would be a really good addition.
Any help on how to work out a similar code would be much appreciated.