Parse and compare addresses with netip
Parse and compare addresses with netip
net/netip provides immutable comparable address values. Addr represents an IP, AddrPort includes a numeric port, and Prefix combines an address and prefix length. Unlike net.IP slices, Addr values can be map keys. Parse functions return errors for invalid input; MustParse is suitable for known constants, not user input.
package main
import ( "fmt" "net/netip")
func main() { a, e := netip.ParseAddrPort("[2001:db8::1]:443") if e != nil { panic(e) } fmt.Println(a.Addr(), a.Port()) p := netip.MustParsePrefix("192.0.2.19/24") fmt.Println(p.Masked()) fmt.Println(p.Contains(netip.MustParseAddr("192.0.2.90")))}Masked clears the host bits; ParsePrefix need not do that automatically. Contains tests address membership, not reachability, authorization or firewall policy. IPv6 endpoints use brackets and a port. A zero Addr is invalid, not the unspecified address 0.0.0.0.
Expected output:
2001:db8::1 443192.0.2.0/24trueNormalize IPv4-mapped IPv6 explicitly
package main
import ( "fmt" "net/netip")
func main() { a := netip.MustParseAddr("::ffff:192.0.2.5") v := netip.MustParseAddr("192.0.2.5") fmt.Println(a == v, a.Unmap() == v) _, e := netip.ParseAddr("999.0.0.1") fmt.Println(e != nil) var zero netip.Addr fmt.Println(zero.IsValid())}Unmap converts IPv4-mapped IPv6 to IPv4 and leaves other addresses alone. Choose normalization consistently before using addresses as keys. IPv6 zone identifiers have scope significance and must not be discarded indiscriminately. Address syntax and prefix membership are not sufficient security policy.
Expected output:
false truetruefalseTry it locally
Check whether 198.51.100.10 and 198.51.100.200 are in 198.51.100.0/25. Print true false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 05: Parse and compare addresses with netip
Check the lesson objective before moving on.
What does Prefix.Masked do?
How should arbitrary address input be parsed?