Classify Addresses With net/netip

Parse IPv4 and IPv6 literals with net/netip, then classify private, loopback, and link-local ranges and test CIDR membership.

GoSecurity Boundaries

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"net/netip"
)

func main() {
	// ParseAddr 只接受 IP 字面量,不做 DNS 解析
	addrs := []string{"192.168.1.10", "127.0.0.1", "203.0.113.7", "fe80::1", "2001:db8::5"}
	for _, raw := range addrs {
		addr, err := netip.ParseAddr(raw)
		if err != nil {
			fmt.Println("bad address:", raw)
			continue
		}
		fmt.Printf("%-12s private=%-5t loopback=%-5t linklocal=%t\n",
			addr, addr.IsPrivate(), addr.IsLoopback(), addr.IsLinkLocalUnicast())
	}

	// Prefix 与 Contains 用于 CIDR 归属判断
	prefix, err := netip.ParsePrefix("10.0.0.0/8")
	if err != nil {
		fmt.Println("bad prefix:", err)
		return
	}
	addr, _ := netip.ParseAddr("10.42.7.9")
	fmt.Println("in 10.0.0.0/8:", prefix.Contains(addr))
	fmt.Println("prefix bits:", prefix.Bits())

	// Unmap 把 IPv4-mapped IPv6 还原成纯 IPv4
	mapped, _ := netip.ParseAddr("::ffff:192.0.2.1")
	fmt.Println("unmapped:", mapped.Unmap(), "is4:", mapped.Unmap().Is4())
}

How it works

Classify Addresses With net/netip is built around the function main.

Repetition is confined to for _, raw := range addrs — the rest of the file is straight-line. Nothing falls through silently — 2 checkpoints test err != nil on the way through.

Using it

The demo output is labeled (bad address:, bad prefix:, in 10.0.0.0/8:), so the output doubles as a step-by-step trace of what the file did.

Key statements

for _, raw := range addrs {
	addr, err := netip.ParseAddr(raw)
	if err != nil {
		fmt.Println("bad address:", raw)
		continue
	}
	fmt.Printf("%-12s private=%-5t loopback=%-5t linklocal=%t\n",
		addr, addr.IsPrivate(), addr.IsLoopback(), addr.IsLinkLocalUnicast())
}
if err != nil {
	fmt.Println("bad prefix:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Classify Addresses With net/netip print when run?
Invoke the file as-is — the `bad address:`, `bad prefix:`, `in 10.0.0.0/8:` prefixes identify which step printed each line.