DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 74: Python Validate IPv4 Address – String Parsing Mastery for Perfect IP Check (No Libraries Needed)

Welcome to Day 74 of the #80DaysOfChallenges journey! This intermediate challenge focuses on validating an IPv4 address string with strict rules, checking for exactly four parts, digit-only segments, no leading zeros, and values between 0-255, using split and manual checks for a robust, library-free solution. It's a practical exercise in string parsing, numeric validation, and edge handling, essential for networking, input sanitization, or backend APIs. If you're building secure systems or practicing precise string logic, this "Python IPv4 validator" script demonstrates a function that's thorough, efficient, and easy to integrate for IP checks.


💡 Key Takeaways from Day 74: IPv4 Validation Function

This task features a function that splits the IP, validates each part with conditions, and returns bool. It's a straightforward parse-validate pattern: split, check count, per-part rules. We'll detail: function with split and length check, loop for part validation, and main with input and result.

1. Function Design: Split and Basic Count Check

The is_valid_ipv4 function takes ip string, returns bool:

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
Enter fullscreen mode Exit fullscreen mode

Splits on '.', checks exactly 4 (e.g., "192.168.1.1" → 4, "1.2.3" → false). Simple first filter.

2. Loop Processing: Per-Part Rules Validation

Core loop checks each part:

    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 < 0 or value > 255:
            return False               # each part must be in range 0–255

    return True
Enter fullscreen mode Exit fullscreen mode

Empty false (e.g., "1..2"). Isdigit for digits only. Leading zero ban (except "0"). Int convert, range 0-255. Covers all invalid like "256", "01", "a".

3. Main Interactive: Input and Bool Print

Script prompts ip, calls, prints:

ip = input("Enter an IPv4 address: ").strip()
result = is_valid_ipv4(ip)

print(f"Is valid IPv4: {result}")
Enter fullscreen mode Exit fullscreen mode

Strip cleans, calls function, prints true/false. Test "192.168.0.1" → true, "192.168.0.256" → false.


🎯 Summary and Reflections

This IPv4 validator uses split and rules for accurate checks. It reinforced:

  • Parse early: Split filters structure fast.
  • Rule layers: Empty/digit/zero/range sequential.
  • No libs: Manual for deep understanding.

Reflections: Handles basics, add subnet for full. Common in networking.

Advanced Alternatives: Regex ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d).?\b){4}$. IPy lib. Your IP validate? Share!


🚀 Next Steps and Resources

Day 74 validated IPs manually. In #80DaysOfChallenges? IPv6? Post!

Top comments (2)

Collapse
 
onlineproxyio profile image
OnlineProxy

A strict IPv4 validator should enforce four ASCII-dot-separated parts, ASCII digits only, no leading zeros, values in [0, 255], and no whitespace, signs, or extra punctuation-no funny business. Give users both: a fast is_valid(ip) -> bool for hot paths and a richer validate(ip) -> Result(...) for great error messages. Also a hard no on leading zeros, empty segments, ports/CIDR, signs, legacy octal/hex, and Unicode confusables under a strict ASCII policy. Back it with a solid test corpus plus property-based tests, log invalids at the edge, and keep validation, normalization, and policy decoupled-default strict, with flags like ascii_only and allow_leading_zeros for when you must loosen up.

Collapse
 
shahrouzlogs profile image
Shahrouz Nikseresht

Thanks a lot for the detailed comment, really appreciate it 🙏🏽

This challenge was mainly about learning and practicing manual string parsing without libraries, but your points gave me a lot to think about for real-world usage.

I’ll definitely keep these ideas in mind as I move forward. Thanks again for sharing your experience!