How to test if the result of netip.ParsePrefix() is IPv6 in Go?

34 Views Asked by At

How can I determine that the CIDR block parsed by netip.ParsePrefix() was in IPv4 or IPv6 format?

  • With net.ParseCIDR() I could call .To4() and test for nil.
  • Is4() is not defined for netip.Prefix.
  • I considered using p.Bits() that that is ambiguous for Prefixes of len 32 or shorter.
        p, err := netip.ParsePrefix(cidr)
        p.Is4() // ERROR!  p.Is4 undefined (type netip.Prefix has no field or method Is4)
1

There are 1 best solutions below

0
TomOnTime On

Call p.Addr() to retrieve the prefix's IP address, then call .Is4() or .Is6() on the address.

For example: p.Addr().Is6()

Or a longer example:

        p, err := netip.ParsePrefix(cidr)
        fmt.Printf("p=%v ipv6=%v, err=%v\n", p, p.Addr().Is6(), err)