fix is_ip_v4_address_valid.py (#12394)

* fix is_ip_v4_address_valid

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update is_ip_v4_address_valid.py

---------

Co-authored-by: m.tavasoli <mehdi.sherkattavasoli@basalam.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
This commit is contained in:
mahdi tavasoli 2024-12-30 13:52:20 +03:30 committed by GitHub
parent f45e392cf6
commit 68b4c6b479
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,13 +1,15 @@
""" """
wiki: https://en.wikipedia.org/wiki/IPv4
Is IP v4 address valid? Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D, A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254 where A, B, C and D are numbers from 0-255
for example: 192.168.23.1, 172.254.254.254 are valid IP address for example: 192.168.23.1, 172.255.255.255 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address 192.168.256.0, 256.192.3.121 are invalid IP address
""" """
def is_ip_v4_address_valid(ip_v4_address: str) -> bool: def is_ip_v4_address_valid(ip: str) -> bool:
""" """
print "Valid IP address" If IP is valid. print "Valid IP address" If IP is valid.
or or
@ -16,13 +18,13 @@ def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
>>> is_ip_v4_address_valid("192.168.0.23") >>> is_ip_v4_address_valid("192.168.0.23")
True True
>>> is_ip_v4_address_valid("192.255.15.8") >>> is_ip_v4_address_valid("192.256.15.8")
False False
>>> is_ip_v4_address_valid("172.100.0.8") >>> is_ip_v4_address_valid("172.100.0.8")
True True
>>> is_ip_v4_address_valid("254.255.0.255") >>> is_ip_v4_address_valid("255.256.0.256")
False False
>>> is_ip_v4_address_valid("1.2.33333333.4") >>> is_ip_v4_address_valid("1.2.33333333.4")
@ -45,12 +47,29 @@ def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
>>> is_ip_v4_address_valid("1.2.3.") >>> is_ip_v4_address_valid("1.2.3.")
False False
>>> is_ip_v4_address_valid("1.2.3.05")
False
""" """
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()] octets = ip.split(".")
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets) if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
return False
number = int(octet)
if len(str(number)) != len(octet):
return False
if not 0 <= number <= 255:
return False
return True
if __name__ == "__main__": if __name__ == "__main__":
ip = input().strip() ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid" valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.") print(f"{ip} is a {valid_or_invalid} IPv4 address.")