Skip to content

ipv4() and ipv6() accept non-string values, and ipv4() raises AttributeError with private= #578

Open

Description

@BingSuBing

Description

ipv4() and ipv6() are annotated as taking value: str, but the value is passed directly to ipaddress.IPv4Address / IPv4Network (and their IPv6 counterparts), which also accept integers, bytes and tuples. As a result, non-string values are reported as valid IP addresses.

Steps to reproduce

>>> import validators
>>> validators.ipv4(True)
True
>>> validators.ipv4(b'\x7f\x00\x00\x01')
True
>>> validators.ipv4(('10.0.0.0', 8))
True
>>> validators.ipv6(1)
True

When private= is set, an integer input raises an exception instead of returning ValidationError, because _check_private_ip() calls value.startswith():

>>> validators.ipv4(3232235777, private=True)
Traceback (most recent call last):
  File ".../src/validators/utils.py", line 88, in wrapper
    if func(*args, **kwargs)
  File ".../src/validators/ip_address.py", line 91, in ipv4
    return IPv4Network(value, strict=not host_bit) and _check_private_ip(value, private)
  File ".../src/validators/ip_address.py", line 24, in <genexpr>
    value.startswith(l_bit)
AttributeError: 'int' object has no attribute 'startswith'

The validator decorator only catches ValueError, TypeError and UnicodeError, so this AttributeError propagates to the caller.

Expected behavior

Non-string values should return ValidationError, the same as other invalid inputs.

Proposed fix

Return False early in both ipv4() and ipv6() when value is not a str:

if not value or not isinstance(value, str):
    return False

I'd be happy to open a PR with this change and tests for bool, int, bytes and tuple inputs.

Environment

  • validators: master (commit 22786cc)
  • Python: 3.14.3
  • OS: Windows

Activity

  1. BingSuBing commented on Nov 21, 2026

    @BingSuBing
    Author

    Hi, I mentioned in this issue that I'd like to open a PR with the fix and tests, and I was preparing one. I see #579 was opened without any prior discussion here. @nandgator , would you prefer I submit my PR as well, or should I review #579 instead? Either way is fine with me, I just wanted to clarify since I'd offered to work on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions