Skip to content

Instantly share code, notes, and snippets.

@x1unix
Last active April 16, 2020 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x1unix/5ff0f83dbbefd8cbaaab565bdebcc900 to your computer and use it in GitHub Desktop.
Save x1unix/5ff0f83dbbefd8cbaaab565bdebcc900 to your computer and use it in GitHub Desktop.
Go - CIDR to IPs
package main
func IPsFromCIDR(cidr string) ([]net.IP, error) {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
ones, bits := ipNet.Mask.Size()
addrCount := 1 << (bits - ones)
ip := ipNet.IP
result := make([]net.IP, 0, addrCount)
for x := 0; x < addrCount; x++ {
result = append(result, cloneIP(ip))
incrementIP(ip)
}
return result, nil
}
func cloneIP(src net.IP) net.IP {
dest := make(net.IP, len(src))
copy(dest, src)
return dest
}
func incrementIP(ip net.IP) {
for i := len(ip) - 1; i >= 0; i-- {
ip[i]++
//only add to the next byte if we overflowed
if ip[i] != 0 {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment