Validate IP Address in Python

IP address validation is a common programming task. We need to determine whether a given string is a valid IPv4 address, IPv6 address, or neither. Each format has specific rules that must be followed.

IPv4 Address Rules

IPv4 addresses consist of four decimal numbers (0-255) separated by dots. Leading zeros are not allowed except for "0" itself ?

  • Valid: 192.168.1.1, 0.0.0.0

  • Invalid: 192.168.01.1 (leading zero), 256.1.1.1 (out of range)

IPv6 Address Rules

IPv6 addresses consist of eight groups of hexadecimal digits (1-4 digits each) separated by colons. Leading zeros within groups can be omitted, but extra leading zeros are invalid ?

  • Valid: 2001:0db8:85a3:0000:0000:8a2e:0370:7334, 2001:db8:85a3:0:0:8A2E:370:7334

  • Invalid: 02001:0db8:85a3:0000:0000:8a2e:0370:7334 (too many digits)

Implementation

class Solution:
    def validIPAddress(self, IP):
        def isIPv4(s):
            try: 
                return str(int(s)) == s and 0 <= int(s) <= 255
            except: 
                return False
        
        def isIPv6(s):
            if len(s) > 4 or len(s) == 0:
                return False
            try: 
                return int(s, 16) >= 0 and s[0] != '-'
            except:
                return False
        
        if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
            return "IPv4"
        if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
            return "IPv6"
        return "Neither"

# Test examples
solution = Solution()

# Test IPv4 addresses
print(solution.validIPAddress("172.16.254.1"))
print(solution.validIPAddress("192.168.01.1"))
print(solution.validIPAddress("256.256.256.256"))

# Test IPv6 addresses
print(solution.validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"))
print(solution.validIPAddress("02001:0db8:85a3:0000:0000:8a2e:0370:7334"))

# Test invalid addresses
print(solution.validIPAddress("192.168@1.1"))
IPv4
Neither
Neither
IPv6
Neither
Neither

How It Works

The solution uses two helper functions ?

  • isIPv4(): Converts string to integer and back to check for leading zeros, then validates range 0-255

  • isIPv6(): Checks length (1-4 characters), converts hexadecimal to integer, and ensures no negative sign

Alternative Using Regular Expressions

import re

def validate_ip_regex(ip):
    # IPv4 pattern
    ipv4_pattern = r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
    
    # IPv6 pattern  
    ipv6_pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
    
    if re.match(ipv4_pattern, ip):
        # Additional check for leading zeros
        parts = ip.split('.')
        for part in parts:
            if len(part) > 1 and part[0] == '0':
                return "Neither"
        return "IPv4"
    elif re.match(ipv6_pattern, ip):
        return "IPv6"
    else:
        return "Neither"

# Test the regex approach
print(validate_ip_regex("172.16.254.1"))
print(validate_ip_regex("2001:0db8:85a3:0:0:8A2E:0370:7334"))
print(validate_ip_regex("192.168.01.1"))
IPv4
IPv6
Neither

Conclusion

IP address validation requires checking format rules and value ranges. The string manipulation approach is more straightforward, while regex offers a more compact solution for complex pattern matching.

Updated on: 2026-03-25T08:25:48+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements