Fix the IPv4 check for untrusted log input
Your task
A log pipeline filtered untrusted input with a regex an AI described as an IPv4 validator. It only checked for four groups of one to three digits, so it let through 999.999.999.999. The replacement checks each part of the address for real.
An assistant wrote is_canonical_ipv4(candidate). It is in the editor. It has a bug. Find it and fix it.
Input and output:
candidate: the string to check.- Return
truewhen it is a canonical IPv4 address, elsefalse.
Rules the tests check:
- Split the string on
.. There must be exactly 4 parts. - Each part must be 1 to 3 characters, all ASCII digits.
- A part longer than one character must not start with
0, so0is fine and010is not. Some parsers read010as octal 8. - Each part's value must be at most 255.
- Nothing is trimmed: any space, tab or other character outside the address makes it invalid.
Examples
is_canonical_ipv4(candidate: str) -> boolExample 1
Input
is_canonical_ipv4("1.2.3.4")Output
TrueExample 2
Input
is_canonical_ipv4("999.999.999.999")Output
FalseExample 3
Input
is_canonical_ipv4("010.0.0.1")Output
False