netip.AddrPort Host Port Pairs

Parse and build host:port pairs with netip.AddrPort, keeping address and port as typed fields instead of splitting strings by hand.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"net/netip"
)

func main() {
	// ParseAddrPort 接受 host:port;只认 IP 字面量,不做 DNS 解析
	for _, raw := range []string{"10.1.2.3:8080", "[2001:db8::1]:443", "10.1.2.3"} {
		ap, err := netip.ParseAddrPort(raw)
		if err != nil {
			fmt.Printf("reject %-18q %v\n", raw, err)
			continue
		}
		fmt.Printf("%-18q addr=%v port=%d ipv6=%t\n",
			raw, ap.Addr(), ap.Port(), ap.Addr().Is6())
	}

	// 从分离的地址与端口组装:端口类型是 uint16,越界值无法塞进来
	ip, err := netip.ParseAddr("192.0.2.10")
	if err != nil {
		fmt.Println("bad ip:", err)
		return
	}
	ap := netip.AddrPortFrom(ip, 9000)
	fmt.Println("built:", ap, "valid:", ap.IsValid())

	// String 输出带方括号的 IPv6 形式,可直接拼进 URL 的 host 段
	v6 := netip.AddrPortFrom(netip.MustParseAddr("2001:db8::5"), 8443)
	fmt.Println("url host:", v6.String())

	// 零值不合法:解析失败时不会悄悄返回一个能用的端口
	fmt.Println("zero valid:", netip.AddrPort{}.IsValid())
}

Parsing host and port pairs

netip.AddrPort Host Port Pairs is built around the function main.

The loop for _, raw := range []string{"10.1.2.3:8080", "[2001:db8::1]:443", "10.1.2.3"} is the only repeated construct. err is inspected at 2 call sites before any result is trusted.

Points of care

  • The import list names net/netip alone; nothing here reaches for a package registry.

Putting it to use

Signature: func main()

The run emits 5 labeled sections — reject, bad ip:, built:, url host:, zero valid: — one per step.

Accept-and-build moments

for _, raw := range []string{"10.1.2.3:8080", "[2001:db8::1]:443", "10.1.2.3"} {
	ap, err := netip.ParseAddrPort(raw)
	if err != nil {
		fmt.Printf("reject %-18q %v\n", raw, err)
		continue
	}
	fmt.Printf("%-18q addr=%v port=%d ipv6=%t\n",
		raw, ap.Addr(), ap.Port(), ap.Addr().Is6())
}
if err != nil {
	fmt.Println("bad ip:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does netip.AddrPort Host Port Pairs print when run?
Run it as a complete program — the output lines carry labels such as `reject`, `bad ip:`, `built:`.