lionsoul2014/ip2region · error

length of the two ips are not the same

Error message

length of the two ips are not the same

What it means

IPAdd adds two fixed-length byte-encoded IP values and requires both inputs to be the same length (4 or 16 bytes). Mismatched lengths mean one operand is IPv4 and the other IPv6, which cannot be added, so it fails fast.

Source

Thrown at binding/golang/xdb/util.go:88

func IPSubOne(ip []byte) []byte {
	var r = make([]byte, len(ip))
	copy(r, ip)
	for i := len(ip) - 1; i >= 0; i-- {
		if r[i] != 0 { // No borrow needed
			r[i]--
			break
		}
		r[i] = 0xFF // borrow from the next byte
	}

	return r
}

// IPAdd Add the spcecified two byte ip
func IPAdd(sip, eip []byte) ([]byte, error) {
	if len(sip) != len(eip) {
		return []byte{}, fmt.Errorf("length of the two ips are not the same")
	}

	var carry uint16 = 0
	var result = make([]byte, len(sip)+1)

	for i := len(sip) - 1; i >= 0; i-- {
		sum := uint16(sip[i]) + uint16(eip[i]) + carry
		result[i+1] = byte(sum) // Store standard 8-bit result
		carry = sum >> 8        // Extract the 1-bit carry for the next byte
	}

	// check and append the carry
	if carry > 0 {
		result[0] = byte(carry)
		return result, nil
	} else {
		return result[1:], nil
	}

View on GitHub (pinned to c1a1fc7d59)

Solutions

  1. Ensure both operands come from the same family: convert both with To4 or both with To16 before calling IPAdd
  2. Reject or skip range pairs whose lengths differ in your data-processing loop
  3. Use IPMiddle only within a single IP version's ranges
  4. Normalize inputs via xdb.ParseIP so both sides get consistent encoding

Example fix

// before
a, _ := xdb.ParseIP("1.2.3.4")     // 4 bytes
b, _ := xdb.ParseIP("::2")        // 16 bytes
m, err := xdb.IPAdd(a, b)          // length mismatch
// after
if len(a) != len(b) { return fmt.Errorf("mixed ip families") }
a16 := net.IP(a).To16()
b16 := net.IP(b).To16()
m, err := xdb.IPAdd(a16, b16)
Defensive patterns

Strategy: type-guard

Validate before calling

func sameFamily(a, b []byte) bool { return len(a) == len(b) }

Type guard

func canIPAdd(sip, eip []byte) bool {
    return (len(sip) == 4 || len(sip) == 16) && len(sip) == len(eip)
}

Try / catch

r, err := xdb.IPAdd(sip, eip)
if err != nil {
    return fmt.Errorf("ip add across families (%d vs %d bytes): %w", len(sip), len(eip), err)
}

Prevention

When it happens

Trigger: Calling IPAdd (directly or via IPMiddle) with a 4-byte slice and a 16-byte slice, e.g. mixing results of ParseIP for "1.2.3.4" and "::1"; computing a middle IP across a range that spans v4 and v6.

Common situations: Data files containing both IPv4 and IPv6 rows iterated with a single range-math routine; user-supplied start/end pairs of different families; code that assumed all IPs are 16 bytes after To16 conversion on one side only.

Related errors


AI-assisted analysis of lionsoul2014/ip2region@c1a1fc7d59 (2026-09-02). Data as JSON: /api/errors/fa1958b177d98ba3. Report an issue: GitHub.