lionsoul2014/ip2region · error · ValueError
invalid bytes ip `{}`
Error message
invalid bytes ip `{}` What it means
util.ip_to_string() formats packed IP bytes as a human-readable string, but only if the input is actually a bytes object; anything else raises ValueError('invalid bytes ip ...'). It is a strict input-type guard used in error messages and utilities.
Source
Thrown at binding/python/ip2region/util.py:75
self.ipVersion,
self.runtimePtrBytes
)
# ---
# ip parse and convert functions
def parse_ip(ip_string: str):
try:
return ipaddress.ip_address(ip_string).packed
except:
raise ValueError("invalid ip address `{}`".format(ip_string))
def ip_to_string(ip_bytes: bytes):
if isinstance(ip_bytes, bytes):
return str(ipaddress.ip_address(ip_bytes))
else:
raise ValueError("invalid bytes ip `{}`".format(ip_bytes))
def ip_compare(ip1: bytes, ip2: bytes):
if ip1 > ip2:
return 1
elif ip1 < ip2:
return -1
else:
return 0
def ip_sub_compare(ip1: bytes, buff: bytes, offset: int):
ip2 = buff[offset:offset+len(ip1)]
if ip1 > ip2:
return 1
elif ip1 < ip2:
return -1
else:
return 0
View on GitHub (pinned to c1a1fc7d59)
Solutions
- Convert to bytes first: bytes(value) if it's bytearray/memoryview, or parse strings with util.parse_ip instead
- Check isinstance(ip_bytes, bytes) before calling
- For string IPs just print them directly instead of round-tripping through ip_to_string
Example fix
# before
util.ip_to_string('1.2.3.4') # str, not bytes
# after
util.ip_to_string(util.parse_ip('1.2.3.4')) # -> '1.2.3.4' Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(ip, bytes):
ip = util.parse_ip(ip) if isinstance(ip, str) else bytes(ip) Type guard
def is_packed_ip(v) -> bool:
return isinstance(v, bytes) and len(v) in (4, 16) Try / catch
try:
text = util.ip_to_string(b)
except ValueError:
text = str(b) # fallback representation Prevention
- Keep a single internal representation (bytes) for IPs
- Convert bytearray/memoryview with bytes() before calling
- Avoid round-tripping: print the original string if you already have it
When it happens
Trigger: Calling ip_to_string with a str, bytearray, memoryview, int, or None instead of bytes/byte-like input.
Common situations: Passing the original string IP back into ip_to_string by mistake; passing a bytearray from decompression; logic that mixes str and bytes forms of the address.
Related errors
- invalid ip address `{}`
- invalid ip address `{}` ({} expected)
- invalid ip address `{}`
- invalid bytes ip, not a Buffer
- invalid byte ip address with length=${ipBytes.length}
AI-assisted analysis of lionsoul2014/ip2region@c1a1fc7d59 (2026-09-02).
Data as JSON: /api/errors/d5867e1dfd6c6469.
Report an issue: GitHub.