Validate IP Address
1 approach, code in every language
Problem description
Given a string, decide whether it is a valid IPv4 address, a valid IPv6 address, or neither. An IPv4 address is four decimal groups separated by dots, where each group is a number from 0 to 255 with no leading zeros (except the single digit 0). An IPv6 address is eight groups separated by colons, where each group has one to four hexadecimal digits and both letter cases are allowed.
Return "IPv4" for a valid IPv4 string, "IPv6" for a valid IPv6 string, and "Neither" for anything that does not fit either format. Empty groups and trailing separators are invalid.
Example 1
Input: queryIP = "10.0.1.38"
Output: "IPv4"
Four groups, each between 0 and 255 with no leading zeros, so it is a valid IPv4 address.
Example 2
Input: queryIP = "2001:0db8:85a3:0:0:8a2e:0370:7334"
Output: "IPv6"
Eight colon-separated groups, each with one to four hexadecimal digits, so it is a valid IPv6 address.
Constraints
1 ≤ queryIP.length ≤ 40queryIP consists of English letters, digits, and the characters '.' and ':'The answer is exactly one of "IPv4", "IPv6", or "Neither"
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Classify a Host Address is our own problem on the technique behind Validate IP Address: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free