valyala/fasthttp · error

value is negative, cannot convert to uint32

Error message

value is negative, cannot convert to uint32

What it means

safeIntToUint32 guards the conversion of an int (e.g. a network interface index used for IPv6 scope) to uint32. If the value is negative it cannot be represented as uint32, so the function returns this error instead of silently wrapping around via the unsigned cast.

Source

Thrown at tcplisten/tcplisten.go:191

		if tcpAddr.Zone != "" {
			ifi, err := net.InterfaceByName(tcpAddr.Zone)
			if err != nil {
				return nil, -1, err
			}
			sa6.ZoneId, err = safeIntToUint32(ifi.Index)
			if err != nil {
				return nil, -1, fmt.Errorf("unexpected convert net interface index int to uint32: %w", err)
			}
		}
		return &sa6, unix.AF_INET6, nil
	default:
		return nil, -1, errors.New("only tcp, tcp4, or tcp6 is supported " + network)
	}
}

func safeIntToUint32(i int) (uint32, error) {
	if i < 0 {
		return 0, errors.New("value is negative, cannot convert to uint32")
	}
	ui := uint64(i)
	if ui > math.MaxUint32 {
		return 0, errors.New("value exceeds uint32 max value")
	}
	return uint32(ui), nil
}

func safeIntToUintptr(i int) (uintptr, error) {
	if i < 0 {
		return 0, errors.New("value is negative, cannot convert to uintptr")
	}
	return uintptr(i), nil
}

View on GitHub (pinned to c96f600972)

Solutions

  1. Inspect the interface index source; ensure it comes from a successful net.InterfaceByName/InterfaceByIndex lookup
  2. Replace -1 sentinels with 0 or omit the interface index when binding on any interface
  3. Validate the index is >= 0 before calling NewListener

Example fix

// before
ifaceIdx := -1 // unset
ln, _ := ctl.NewListener("tcp6", addr) // safeIntToUint32(-1) errors
// after
ifaceIdx := 0 // 0 = any interface
ln, _ := ctl.NewListener("tcp6", addr)
Defensive patterns

Strategy: validation

Validate before calling

func validateIfaceIndex(idx int) error {
  if idx < 0 { return fmt.Errorf("interface index must be >= 0, got %d", idx) }
  return nil
}

Type guard

func isUint32Safe(i int) bool { return i >= 0 && uint64(i) <= math.MaxUint32 }

Try / catch

ln, err := ctl.NewListener(network, addr)
if err != nil {
  if strings.Contains(err.Error(), "value is negative, cannot convert to uint32") {
    return fmt.Errorf("invalid interface index %d: %w", ifaceIdx, err)
  }
  return err
}

Prevention

When it happens

Trigger: getSockaddr passes a negative interface index (from net.InterfaceByIndex or similar) into safeIntToUint32 while building an AF_INET6 sockaddr — typically when an interface lookup failed or returned -1 as an 'unset' sentinel.

Common situations: Using a -1 interface index placeholder for 'any interface'; failed or uninitialized interface lookups; a configuration field like zone/interface index set to -1 in yaml/env.

Related errors


AI-assisted analysis of valyala/fasthttp@c96f600972 (2026-08-31). Data as JSON: /api/errors/c5afd0139879e54a. Report an issue: GitHub.