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
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:])
}
package main
import (
"errors"
"fmt"
"net"
)
func expandIPv6Addr(s string) (string, error) {
addr := net.ParseIP(s).To16()
if addr == nil {
return "", ErrInvalidAddress
}
var hex [16 * 3]byte
for i := 0; i < len(addr); i++ {
if i > 0 {
hex[3*i-1] = ':'
}
hex[3*i] = nibbleToChar(addr[i] >> 4)
hex[3*i+1] = nibbleToChar(addr[i])
}
return string(hex[:]), nil
}
func nibbleToChar(b byte) byte {
b &= 0x0f
if b > 9 {
return ('a' - 10) + b
}
return '0' + b
}
var ErrInvalidAddress = errors.New("invalid address")
func main() {
ipv6 := "fe80:01::af0"
fmt.Println(ipv6)
fmt.Println(expandIPv6Addr(ipv6))
}