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:
|
|
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.