Skip to content

Instantly share code, notes, and snippets.

@Tugzrida
Last active November 10, 2024 03:59
Show Gist options
  • Save Tugzrida/341a5471d6e2afc278c541998b56e0a0 to your computer and use it in GitHub Desktop.
Save Tugzrida/341a5471d6e2afc278c541998b56e0a0 to your computer and use it in GitHub Desktop.
go function to generate all the reverse DNS delegations needed to cover a netip.Prefix
package main
import (
"fmt"
"net/netip"
"strconv"
"strings"
)
func PrefixDelegs(p netip.Prefix) []string {
if !p.IsValid() {
return nil
}
prefixLen := p.Bits()
addr := p.Masked().Addr()
var (
baseZone string
bitsPerLabel int
labelRadix int
labels []string
)
if addr.Is6() {
baseZone = "ip6.arpa"
bitsPerLabel = 4
labelRadix = 16
labels = strings.Split(strings.ReplaceAll(addr.StringExpanded(), ":", ""), "")
} else {
baseZone = "in-addr.arpa"
bitsPerLabel = 8
labelRadix = 10
labels = strings.Split(addr.String(), ".")
}
numFixedLabels, remFixedBits := prefixLen/bitsPerLabel, prefixLen%bitsPerLabel
for _, l := range labels[:numFixedLabels] {
baseZone = l + "." + baseZone
}
// baseZone is now the closest enclosing zone for the prefix
if remFixedBits == 0 {
// Prefix length aligns with label boundary, return single zone
return []string{baseZone}
}
// Multiple zones are needed to cover prefix, start with current first non-fixed label
// up to maximum value able to be represented by remaining non-fixed bits
lastLabel, _ := strconv.ParseUint(labels[numFixedLabels], labelRadix, bitsPerLabel)
lastLabelEnd := lastLabel + 1<<(bitsPerLabel-remFixedBits) - 1
var zones []string
for ; lastLabel <= lastLabelEnd; lastLabel++ {
zones = append(zones, strconv.FormatUint(lastLabel, labelRadix)+"."+baseZone)
}
return zones
}
func main() {
fmt.Printf("%+v\n", PrefixDelegs(netip.MustParsePrefix("2001:db8:8000::/33")))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment