How to Parse and Build IP Addresses in Go

Web
Use net.ParseIP to convert strings to IP objects and IP.String() to convert them back.

Use the net package's ParseIP function to parse strings and IP.String() to format them.

package main

import (
	"fmt"
	"net"
)

func main() {
	// Parse
	ip := net.ParseIP("192.168.1.1")
	if ip == nil {
		fmt.Println("Invalid IP")
		return
	}

	// Build/Format
	fmt.Println(ip.String()) // Output: 192.168.1.1

	// Build from bytes
	ip2 := net.IPv4(10, 0, 0, 1)
	fmt.Println(ip2.String()) // Output: 10.0.0.1
}