Split Host Port Handles IPv6 Brackets

SplitHostPort separates host and port with required brackets for IPv6 literals, and JoinHostPort adds them back when joining either address family.

GoCli Tooling

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"net"
)

func main() {
	// IPv4:host:port 直接拆分
	host, port, err := net.SplitHostPort("10.0.0.7:5432")
	fmt.Println("v4:", host, port, err)

	// IPv6 地址本身带冒号:必须用方括号包裹才能区分端口
	host, port, err = net.SplitHostPort("[2001:db8::1]:443")
	fmt.Println("v6:", host, port, err)

	// 缺端口:SplitHostPort 返回错误而不是猜一个
	_, _, err = net.SplitHostPort("2001:db8::1")
	fmt.Println("missing port:", err != nil)

	// JoinHostPort 反向拼回:IPv6 自动补上方括号
	fmt.Println("join v4:", net.JoinHostPort("127.0.0.1", "8080"))
	fmt.Println("join v6:", net.JoinHostPort("2001:db8::1", "8080"))
}

Walking through the code

The working parts are the function main — everything else is wiring.

Watch out for

  • The dependency list is empty — the language runtime covers everything.

Applying it

The signature worth starting from: func main()

Output lines are prefixed (v4:, v6:, missing port:), which makes the effect of each step easy to see.

Statements that matter

host, port, err = net.SplitHostPort("[2001:db8::1]:443")

Interactive Tools for This Topic

FAQ

What does Split Host Port Handles IPv6 Brackets print when run?
The script runs standalone; its 5 labeled outputs include `v4:`, `v6:`, `missing port:`.