Reputation: 343
Is there anyway to retrieve the maximum numbers of IPv6 from a CIDR range? Currently I have this code:
package main
import (
"fmt"
"log"
"net"
)
func main() {
ip, ipnet, err := net.ParseCIDR("2001:200:905::/49")
var ips []string
if err != nil {
log.Fatal(err)
}
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
ips = append(ips, ip.String())
}
fmt.Println(len(ips))
}
func inc(ip net.IP) {
for j := len(ip)-1; j>=0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
But this process runs so slow. Is there any efficient way of retrieving the total number of ip addresses?
Upvotes: 0
Views: 1372
Reputation: 4615
The IPAddress Go library can do this (get the count, starting point, end, or any address in the middle) with a few lines of polymorphic code that works with both IPv4 and IPv6 addresses. Repository here. Disclaimer: I am the project manager.
func details(addrStr string) {
addr := ipaddr.NewIPAddressString(addrStr).GetAddress()
lower, upper := addr.GetLower(), addr.GetUpper()
count := addr.GetCount()
fmt.Printf("%s has size %d,\n\tranging from %v to %v\n",
addr, count, lower, upper)
fmt.Println("\thundredth address is", addr.Increment(100))
}
Using your IPv6 example as well as an IPv4 subnet:
details("2001:200:905::/49")
details("192.168.10.0/24")
Output:
2001:200:905::/49 has size 604462909807314587353088,
ranging from 2001:200:905::/49 to 2001:200:905:7fff:ffff:ffff:ffff:ffff/49
hundredth address is 2001:200:905::64/49
192.168.10.0/24 has size 256,
ranging from 192.168.10.0/24 to 192.168.10.255/24
hundredth address is 192.168.10.100/24
Upvotes: 1