[Python] Python IPv4 Validation Only Checking First Byte Instead of All Four Bytes

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a Python function to validate IPv4 addresses. for a Task of CS50 Python. My function should:

    Ensure the format is X.X.X.X, where each X is a number between 0-255. Return True for valid IPv4 addresses and False otherwise.

    However, my test case is failing with this error message:

    :( test_numb3rs.py catches numb3rs.py only checking if first byte of IPv4 address is in range**


    check50 error

    my main code is:

    import re

    def main():
    print(validate(input("IPv4 Address: ")))

    def validate(ip):
    match = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", ip)
    return bool(match) and all(0 <= int(octet) <= 255 for octet in match.groups())

    if __name__ == "__main__":
    main()



    and my Test Code is:

    from numb3rs import validate
    def test_validate():
    # Valid cases
    assert validate("127.0.0.1") == True
    assert validate("255.255.255.255") == True

    # Invalid cases
    assert validate("512.512.512.512") == False
    assert validate("1.2.3.1000") == False
    assert validate("cat") == False



    I have tried following multiple solutions available but still could not understand the issue. I Tried using exit(1) in a different version of my code, but that also did not solve the issue. Instead, it made the cases where any one octet goes above 255 fail.

    Continue reading...

Compartilhe esta Página