TheAlgorithms/Python · error · ValueError
Invalid decimal IPv4 address
Error message
Invalid decimal IPv4 address
What it means
Raised by decimal_to_ipv4(decimal_ipv4) in conversions/ipv4_conversion.py:72 when the integer is outside 0..4294967295 (2**32 - 1). An IPv4 address is exactly 32 bits; negative numbers or values above the unsigned 32-bit maximum cannot map to one, so the function raises ValueError('Invalid decimal IPv4 address') before extracting octets.
Source
Thrown at conversions/ipv4_conversion.py:72
Args:
decimal_ipv4: An integer representing the decimal IP address.
Returns:
The IPv4 representation of the decimal IP address.
>>> decimal_to_ipv4(3232235521)
'192.168.0.1'
>>> decimal_to_ipv4(167772415)
'10.0.0.255'
>>> decimal_to_ipv4(-1)
Traceback (most recent call last):
...
ValueError: Invalid decimal IPv4 address
"""
if not (0 <= decimal_ipv4 <= 4294967295):
raise ValueError("Invalid decimal IPv4 address")
ip_parts = []
for _ in range(4):
ip_parts.append(str(decimal_ipv4 & 255))
decimal_ipv4 >>= 8
return ".".join(reversed(ip_parts))
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Mask to 32 bits before calling: decimal_to_ipv4(value & 0xFFFFFFFF) when wrapping is the intended semantics
- Unpack network words as unsigned: struct.unpack('<I', data) rather than '<i'
- Range-check at your boundary: if not 0 <= value <= 4294967295: reject
Example fix
# before
signed, = struct.unpack('<i', word)
decimal_to_ipv4(signed) # negative -> ValueError
# after
unsigned, = struct.unpack('<I', word)
decimal_to_ipv4(unsigned) Defensive patterns
Strategy: validation
Validate before calling
if not 0 <= decimal_ipv4 <= 0xFFFFFFFF:
raise ValueError(f'{decimal_ipv4} is not an unsigned 32-bit value') Type guard
def is_u32(v: object) -> TypeGuard[int]:
return isinstance(v, int) and 0 <= v <= 0xFFFFFFFF Prevention
- Unpack network words as unsigned ('<I' not '<i')
- Mask with & 0xFFFFFFFF when wrapping is intended
- Range-check hash/CRC outputs before treating them as IPv4 integers
When it happens
Trigger: decimal_to_ipv4(-1), decimal_to_ipv4(2**32), or decimal values produced by signed 32-bit arithmetic, struct unpacking with signed formats, or unchecked increments.
Common situations: Reading 32-bit words unpacked as signed integers ('<i' instead of '<I'); converting hash/CRC values that exceed 2**32; off-by-one loop bounds when enumerating address ranges.
Related errors
- Invalid IPv4 octet {octet}
- Invalid IPv4 address format
- base must be >= 2
- base must be <= 36
- No input value was provided
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/a6fa64f86f1ac632.
Report an issue: GitHub.