goipv6glide-golang

Convert string representing hex number to ipv6


I have this string representing hex:

00000000ff00ff00000900000600020a

I'm trying to convert it to IPv6 with net package

the result I'm expecting is(big endian):

20a:600::9:ff00:ff00::

I tried this:

    ip := "00000000ff00ff00000900000600020a"
    res := make(net.IP, net.IPv6len)
    var err error
    res,err = hex.DecodeString(ip)
    if err != nil {
        fmt.Println("error")
    }
    for i := 0; i < 16/2; i++ {
        res[i], res[16-1-i] = res[16-1-i], res[i]
    }
    fmt.Println(res.String())

but I'm getting this:

a02:6:0:900:ff:ff::

Thanks!


Solution

  • Try this:

    for i := 0; i < 16/2; i += 2 {
        res[i], res[16-2-i] = res[16-2-i], res[i]
        res[i+1], res[16-1-i] = res[16-1-i], res[i+1]
    }
    

    bytes goes in pair, so you need to flip both at time