Validate IP Address

We’ll write a function to determine whether a given IP address string is a valid IPv4, IPv6, or neither. Let’s break down how we can validate each type of IP address.

IPv4

  • It must have 4 parts separated by dots ‘.’.
  • Each part must be an integer between 0 and 255.
  • No part can have leading zeros unless it is 0.

IPv6

  • It must have 8 parts separated by colons ‘:’.
  • Each part must be a hexadecimal string with 1 to 4 characters.
  • Leading zeros are allowed.

Here’s the code that checks these rules:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        def isIPv4(s):
            try:
                return str(int(s)) == s and 0 <= int(s) <= 255
            except:
                return False

        def isIPv6(s):
            if len(s) > 4:
                return False
            try:
                int(s, 16)
                return True
            except:
                return False

        if queryIP.count('.') == 3 and all(isIPv4(i) for i in queryIP.split('.')):
            return "IPv4"
        if queryIP.count(':') == 7 and all(isIPv6(i) for i in queryIP.split(':')):
            return "IPv6"
        return "Neither"

Examples

For queryIP = "172.16.254.1", the output will be "IPv4". For queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334", the output will be "IPv6". For queryIP = "256.256.256.256", the output will be "Neither".

Complexity Analysis

  • Time Complexity: The time complexity for this code is (O(N)), where (N) is the length of the input string queryIP.
  • Space Complexity: The space complexity is (O(1)) since we only use a constant amount of extra space.