Search code examples
goformattingip-addressipv6ipv4

How can I get a string representation of an IPv4-mapped IPv6 that does not use a dotted quad?


Consider, for example, this IPv4-mapped IPv6 address: ::ffff:7f7f:7f7f. When submitting http://[::ffff:7f7f:7f7f] in the address bar of all browsers I've tested, the format is retained:

omnibox

However, the netip package (more specifically, the String method of netip.Addr) formats the address in question by writing its least-significant 32 bits in the IPv4 dot-decimal notation, like so: ::ffff:127.127.127.127.

package main

import (
    "fmt"
    "log"
    "net/netip"
)

func main() {
    ip, err := netip.ParseAddr("::ffff:7f7f:7f7f")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(ip) // ::ffff:127.127.127.127
}

(playground)

I need to replicate the way browsers' address bar format IPv4-mapped IPv6 addresses. Is there any way to get netip to format ::ffff:7f7f:7f7f, not as ::ffff:127.127.127.127, but as ::ffff:7f7f:7f7f?


Solution

  • First, remember that IPv4-Mapped IPv6 addresses are not allowed to be used on a network, as explained in the IANA IPv6 Special-Purpose Address Registry, Notice that they cannot be used as source or destination addresses, cannot be forwarded or globally routable, and they are reserved by IP itself They are not actual IPv6 addresses, only a representation of IPv4 addresses in the IPv6 format in order to have a common address store, e.g. database. They should not work in your browser.