Validate IP Address LeetCode Solution

Here, We see Validate IP Address LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Validate IP Address LeetCode Solution

Validate IP Address LeetCode Solution

Problem Statement

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😡2😡3😡4😡5😡6😡7😡8” 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.

Validate IP Address LeetCode Solution C++

class Solution {
public:
    string validIPAddress(string queryIP) {
        regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"), ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
        if(regex_match(queryIP, ipv4))
            return "IPv4";
        else if(regex_match(queryIP, ipv6))
            return "IPv6";
        return "Neither";      
    }
};Code language: C++ (cpp)

Validate IP Address LeetCode Solution Java

class Solution {
    public String validIPAddress(String queryIP) {
        if(queryIP.length()==0) return "Neither";
        if(queryIP.indexOf(".")>=0) return validateIPV4(queryIP);
        if(queryIP.indexOf(":")>=0) return validateIPV6(queryIP);
        return "Neither";
    }
    private  String validateIPV4(String ip){
        if(ip.charAt(0)=='.' || ip.charAt(ip.length()-1)=='.') return "Neither";
          String[] component=ip.split("\\.");
           if(component.length!=4) return "Neither";
           for(String comp:component){
             if(comp.length()==0 || comp.length()>3 || (comp.charAt(0)=='0' && comp.length()>1)){
                 return "Neither";
             }
              for(char ch:comp.toCharArray()){
                  if(ch<'0' || ch>'9') return "Neither";
              }
              int num=Integer.parseInt(comp);
              if(num<0 || num>255) return "Neither";
           }
           return "IPv4";
           }
   private String validateIPV6(String ip){
     if(ip.charAt(0)==':' || ip.charAt(ip.length()-1)==':') return "Neither";
       String[] component=ip.split(":");
       if(component.length!=8) return "Neither";
       for(String comp:component){
       if(comp.length()==0 || comp.length()>4) return "Neither";
           for(char ch:comp.toLowerCase().toCharArray()){
             if((ch<'0' || ch>'9') && (ch!='a' && ch!='b' && ch!='c' && ch!='d' && ch!='e' && ch!='f')){
                 return "Neither";
             }  
           }
       }
       return "IPv6";
     }
 }Code language: Java (java)

Validate IP Address Solution JavaScript

var validIPAddress = function(queryIP) {
    const ipv4 = /^((\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.){4}$/;
    const ipv6 = /^([\da-f]{1,4}:){8}$/i;
    return ipv4.test(queryIP + '.') ? 'IPv4' : ipv6.test(queryIP + ':') ? 'IPv6' : 'Neither';    
};Code language: JavaScript (javascript)

Validate IP Address Solution Python

class Solution(object):
    def validIPAddress(self, queryIP):
        res = 0
        ipv4 = queryIP.split('.')
        if len(ipv4) == 4:
            for x in ipv4:
                if x == '' or (x[0] == '0' and len(x) != 1) or not x.isdigit() or int(x) > 255:
                    res = 1
                    break
            if not res:
                return 'IPv4'
        ipv6 = queryIP.split(':')
        if len(ipv6) == 8:
            for x in ipv6:
                if x == '' or len(x) > 4 or not all(c in hexdigits for c in x):
                    res = 1
                    break
            if not res:
                return 'IPv6'
        return 'Neither'Code language: Python (python)
Scroll to Top