Go: Normalize IPv4-mapped addresses before using map keys
An IPv4 address and its IPv4-mapped IPv6 form are different netip.Addr values. If a counter should treat them as the same address, apply Unmap before both storing and looking up keys.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as netip_unmap_address_keys.go:
package main
import (
"fmt"
"net/netip"
)
func main() {
counts := make(map[netip.Addr]int)
for _, input := range []string{"192.0.2.1", "::ffff:192.0.2.1", "2001:db8::1"} {
addr, err := netip.ParseAddr(input)
if err != nil {
panic(err)
}
key := addr.Unmap()
counts[key]++
fmt.Printf("%s: mapped=%t key=%s count=%d\n", addr, addr.Is4In6(), key, counts[key])
}
fmt.Println("distinct keys:", len(counts))
}go run netip_unmap_address_keys.goObserved output:
192.0.2.1: mapped=false key=192.0.2.1 count=1
::ffff:192.0.2.1: mapped=true key=192.0.2.1 count=2
2001:db8::1: mapped=false key=2001:db8::1 count=1
distinct keys: 2Read the result
The first two inputs increment the same counter. The ordinary IPv6 address remains unchanged. Printing during insertion avoids depending on map iteration order. All addresses are documentation examples; the program opens no network connections.
Apply it carefully
Use this normalization only when the application intends those address forms to be equivalent. Apply the same rule at every lookup boundary. It does not resolve hostnames, establish peer identity, or make a client-supplied address trustworthy. The panic is limited to these fixed literals; handle parse errors when accepting external input.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- netip_unmap_address_keys.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.