#468
Validate IP Address
expert · 1200 · lc medium +32 · verified · 28.2% accepted · 1,120 likes · top 6%
Description
Inspect the string queryIP and return "IPv4" if it is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, or "Neither" otherwise.
A valid IPv4 address has the form "x1.x2.x3.x4" where each part is a decimal integer in [0, 255] with no leading zeros ("192.168.1.1" is valid; "192.168.01.1" is not).
A valid IPv6 address has the form "x1:x2:x3:x4:x5:x6:x7:x8" where each part is 1–4 hexadecimal characters (0–9, a–f, A–F) and leading zeros are allowed.
Example 1:
Input: queryIP = "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: queryIP = "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.
Code
1
2
3