jackc/pgx · error

cannot scan to *net.IP

Error message

cannot scan %v to *net.IP

What it means

Returned by netIPWrapper.ScanNetipPrefix when the prefix's bit count is less than the address bit length — i.e. the netip.Prefix carries subnet mask information that would be lost, because net.IP stores only a bare address with no mask.

Solutions

  1. Scan into netip.Prefix or net.IPNet to preserve the network mask
  2. Store the value as inet with /32 or /128 so no mask information exists
  3. Truncate the address to its prefix in the query before scanning
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgtype/builtin_wrappers.go:553 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/f047ba1c8c308b04. Report an issue: GitHub.

Appendix: source

Thrown at pgtype/builtin_wrappers.go:553

	}

	ones, _ := w.Mask.Size()

	return netip.PrefixFrom(ip, ones), nil
}

type netIPWrapper net.IP

func (w netIPWrapper) SkipUnderlyingTypePlan() {}

func (w *netIPWrapper) ScanNetipPrefix(v netip.Prefix) error {
	if !v.IsValid() {
		*w = nil
		return nil
	}

	if v.Addr().BitLen() != v.Bits() {
		return fmt.Errorf("cannot scan %v to *net.IP", v)
	}

	*w = netIPWrapper(v.Addr().AsSlice())
	return nil
}

func (w netIPWrapper) NetipPrefixValue() (netip.Prefix, error) {
	if w == nil {
		return netip.Prefix{}, nil
	}

	addr, ok := netip.AddrFromSlice([]byte(w))
	if !ok {
		return netip.Prefix{}, errors.New("invalid net.IP")
	}

	return netip.PrefixFrom(addr, addr.BitLen()), nil
}

View on GitHub (pinned to ec1a0befd2)