Is there an inbuilt function to expand ipv6 addresses?

Issue

I’m working on a project where I need to expand IPv6 addresses. Is there an inbuilt function in Go?

What I’m currently doing is

ipv6 := "fe80:01::af0"
addr := net.ParseIP(ipv6)
fmt.Println(addr.String())

but this still prints

fe80:01::af0

What I actually need is

fe80:0001:0000:0000:0000:0000:0000:0af0

Solution

There’s nothing in the standard library to do this, but it’s easy to write your own function. One possible approach (of many):

func FullIPv6(ip net.IP) string {
    dst := make([]byte, hex.EncodedLen(len(ip)))
    _ = hex.Encode(dst, ip)
    return string(dst[0:4]) + ":" +
        string(dst[4:8]) + ":" +
        string(dst[8:12]) + ":" +
        string(dst[12:16]) + ":" +
        string(dst[16:20]) + ":" +
        string(dst[20:24]) + ":" +
        string(dst[24:28]) + ":" +
        string(dst[28:])
}

Playground

Answered By – Flimzy

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.