Day 74: Python Validate IPv4 Address – String Parsing Mastery for Perfect IP Check (No Libraries Needed)
Source: Dev.to
Key Takeaways from Day 74: IPv4 Validation Function
Function Design: Split and Basic Count Check
def is_valid_ipv4(ip: str) -> bool:
"""Return True if the given string is a valid IPv4 address."""
parts = ip.split(".") # split address into parts
if len(parts) != 4:
return False # IPv4 must have exactly 4 parts
Loop Processing: Per‑Part Rules Validation
for part in parts:
if part == "":
return False # empty segment is invalid
if not part.isdigit():
return False # must contain digits only
if len(part) > 1 and part[0] == "0":
return False # no leading zeros allowed
value = int(part)
if value 255:
return False # each part must be in range 0–255
return True
Main Interactive: Input and Bool Print
ip = input("Enter an IPv4 address: ").strip()
result = is_valid_ipv4(ip)
print(f"Is valid IPv4: {result}")
Summary and Reflections
This IPv4 validator uses split and layered rules for accurate checks.
- Parse early – splitting filters the structure quickly.
- Rule layers – empty segment, digit‑only, leading zero, and range checks are applied sequentially.
- No external libraries – manual validation deepens understanding of string parsing and numeric constraints.
Potential extensions include subnet validation or IPv6 support.
Next Steps and Resources
- Source Code for Challenge #74: scripts/validate_ipv4.py
- Main Repository: 80-days-of-challenges
- Daily Updates: Twitter/X (@Shahrouzlogs)