crowdsecurity/crowdsec · error

unexpected len %d for %s

Error message

unexpected len %d for %s

What it means

IP2Ints converts a net.IP to (size, network-int, suffix-int) by first trying To4(), then To16(). If both conversions return nil, the IP has an unsupported/invalid byte representation and this error is returned with the actual length. This happens for nil net.IP or IPs whose internal representation is empty.

Source

Thrown at pkg/types/ip.go:117

func IP2Ints(pip net.IP) (int, int64, int64, error) {
	var ip_nw, ip_sfx uint64

	pip4 := pip.To4()
	pip16 := pip.To16()

	if pip4 != nil {
		ip_nw32 := binary.BigEndian.Uint32(pip4)
		return 4, uint2int(uint64(ip_nw32)), uint2int(ip_sfx), nil
	}

	if pip16 != nil {
		ip_nw = binary.BigEndian.Uint64(pip16[0:8])
		ip_sfx = binary.BigEndian.Uint64(pip16[8:16])

		return 16, uint2int(ip_nw), uint2int(ip_sfx), nil
	}

	return -1, 0, 0, fmt.Errorf("unexpected len %d for %s", len(pip), pip)
}

View on GitHub (pinned to 909b515798)

Solutions

  1. Validate before calling: if ip == nil || ip.To16() == nil { return/parse again }
  2. Use net.ParseIP on the original string and handle the nil return at parse time
  3. Check upstream parsing: ensure hostnames are resolved (or rejected) before reaching IP conversion
  4. Read the error's len/pip values — len 0 with empty IP almost always means a nil or unset net.IP

Example fix

// before
ip := net.ParseIP(entry) // entry is "example.com" -> nil
sz, _, _, err := types.IP2Ints(ip)
// after
ip := net.ParseIP(entry)
if ip == nil || ip.To16() == nil {
    return fmt.Errorf("'%s' is not a valid IP address", entry)
}
sz, _, _, err := types.IP2Ints(ip)
Defensive patterns

Strategy: validation

Validate before calling

if ip == nil || ip.To16() == nil { return fmt.Errorf("not a valid IP: %q", raw) }

Type guard

func isUsableIP(ip net.IP) bool { return ip != nil && ip.To4() != nil || ip.To16() != nil }

Try / catch

if err != nil {
    if strings.Contains(err.Error(), "unexpected len") {
        // fall back: re-parse the raw string with net.ParseIP and surface it to the user
    }
    return err
}

Prevention

When it happens

Trigger: Calling IP2Ints directly (or via Range2Ints/Addr2Ints) with a nil net.IP, a net.IP built from an empty or zero-length byte slice, or a struct where the IP field was never populated.

Common situations: Parsing empty strings from config (net.ParseIP("") returns nil); a whitelist/blacklist entry that is a hostname rather than an IP reaching this code; IPs returned nil from map lookups or failed DNS resolution; zero-value net.IP variables.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of crowdsecurity/crowdsec@909b515798 (2026-09-06). Data as JSON: /api/errors/f3389163d49ffa97. Report an issue: GitHub.