Algorithm
Problem Name: 468. Validate IP Address
Given a string queryIP
, return "IPv4"
if IP is a valid IPv4 address, "IPv6"
if IP is a valid IPv6 address or "Neither"
if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4"
where 0 <= xi <= 255
and xi
cannot contain leading zeros. For example, "192.168.1.1"
and "192.168.1.0"
are valid IPv4 addresses while "192.168.01.1"
, "192.168.1.00"
, and "192.168@1.1"
are invalid IPv4 addresses.
A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8"
where:
1 <= xi.length <= 4
xi
is a hexadecimal string which may contain digits, lowercase English letter ('a'
to'f'
) and upper-case English letters ('A'
to'F'
).- Leading zeros are allowed in
xi
.
For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
and "2001:db8:85a3:0:0:8A2E:0370:7334"
are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334"
and "02001:0db8:85a3:0000:0000:8a2e:0370:7334"
are invalid IPv6 addresses.
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.
Constraints:
queryIP
consists only of English letters, digits and the characters'.'
and':'
.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public String validIPAddress(String IP) {
if (IP.indexOf(':') != -1) {
return validateIPv6(IP);
}
else if (IP.indexOf('.') != -1) {
return validateIPv4(IP);
}
else {
return "Neither";
}
}
private String validateIPv6(String ip) {
int count = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ip.length(); i++) {
if (ip.charAt(i) == ':') {
if (!isValidIPv6(sb.toString())) {
return "Neither";
}
sb = new StringBuilder();
count++;
}
else {
sb.append(ip.charAt(i));
}
if (i == ip.length() - 1) {
if (!isValidIPv6(sb.toString())) {
return "Neither";
}
}
}
return count == 7 ? "IPv6" : "Neither";
}
private boolean isValidIPv6(String s) {
String lower = "abcdef";
String upper = "ABCDEF";
if (s.length() == 0 || s.length() > 4) {
return false;
}
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
if (lower.indexOf(c) == -1 && upper.indexOf(c) == -1) {
return false;
}
}
}
return true;
}
private String validateIPv4(String ip) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < ip.length(); i++) {
if (ip.charAt(i) == '.') {
if (!isValidIPv4(sb.toString())) {
return "Neither";
}
sb = new StringBuilder();
count++;
}
else {
if (!Character.isDigit(ip.charAt(i))) {
return "Neither";
}
sb.append(ip.charAt(i));
}
if (i == ip.length() - 1) {
if (!isValidIPv4(sb.toString())) {
return "Neither";
}
}
}
return count == 3 ? "IPv4" : "Neither";
}
private boolean isValidIPv4(String s) {
if (s.length() == 0) {
return false;
}
try {
int val = Integer.parseInt(s);
if (val < 0 || val > 255) {
return false;
}
if ((s.startsWith("0") && val != 0) || (val == 0 && s.length() > 1)) {
return false;
}
}
catch (NumberFormatException e) {
return false;
}
return true;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const validIPAddress = function (IP) {
if (IP.indexOf('.') > 0) return validIPv4(IP) ? 'IPv4' : 'Neither'
else return validIPv6(IP) ? 'IPv6' : 'Neither'
}
const validIPv4 = function (IP) {
const strs = IP.split('.')
if (strs.length !== 4) return false
for (let str of strs) {
if (str.length === 0) return false
if (str.match(/[^0-9]/)) return false
if (str.length > 1 && str.charAt(0) === '0') return false
if (+str > 255) return false
}
return true
}
const validIPv6 = function (IP) {
const strs = IP.split(':')
if (strs.length !== 8) return false
for (let str of strs) {
if (str.length === 0) return false
if (str.length > 4) return false
if (str.match(/[^0-9a-fA-F]/g)) return false
}
return true
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
ip4, ip6 = IP.split("."), IP.split(":")
if len(ip4) == 4:
for num in ip4:
try:
if not (num[0] in string.digits and int(num) < 256 and (num[0] != "0" or num == "0")): return "Neither"
except: return "Neither"
return "IPv4"
elif len(ip6) == 8:
for num in ip6:
try:
if not (num[0] in string.hexdigits and 0 <= int(num, 16) and len(num) <= 4): return "Neither"
except: return "Neither"
return "IPv6"
return "Neither"
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
using System.Linq;
namespace LeetCode
{
public class _0468_ValidateIPAddress
{
public string ValidIPAddress(string IP)
{
if (IP.Count(ch => ch == '.') == 3)
return ValidateIPv4(IP) ? "IPv4" : "Neither";
if (IP.Count(ch => ch == ':') == 7)
return ValidateIPv6(IP) ? "IPv6" : "Neither";
return "Neither";
}
private bool ValidateIPv4(string IP)
{
var nums = IP.Split(new char[] { '.' }, StringSplitOptions.None);
foreach (var x in nums)
{
if (x.Length == 0 || x.Length > 3) return false;
if (x[0] == '0' && x.Length != 1) return false;
foreach (var ch in x)
if (!char.IsDigit(ch)) return false;
if (int.Parse(x) > 255) return false;
}
return true;
}
private bool ValidateIPv6(string IP)
{
string hexdigits = "0123456789abcdefABCDEF";
var nums = IP.Split(new char[] { ':' }, StringSplitOptions.None);
foreach (var x in nums)
{
if (x.Length == 0 || x.Length > 4) return false;
foreach (var ch in x)
if (hexdigits.IndexOf(ch) == -1) return false;
}
return true;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output