In this Leetcode Validate IP Address problem solution 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 but "192.168.01.1", while "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, lower-case English letter ('a' to 'f') and upper-case English letters ('A' to 'F').

Leading zeros are allowed in xi.

Leetcode Validate IP Address problem solution


Problem solution in Python.

class Solution:
    def validIPAddress(self, IP):
        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"


Problem solution in Java.

public String validIPAddress(String IP) {
        if(IP == null || IP.length() == 0) return "Neither";
        if(isValidIPv4(IP)) return "IPv4";
        if(isValidIPv6(IP)) return "IPv6";
        return "Neither";
    }
    public boolean isValidIPv4(String IP){
        String[] input = IP.split("\\.");
        //1.1 or 1.1.1.1.
        if(input.length != 4 || IP.charAt(IP.length() - 1) == '.') return false;
        for(String s : input){
            if(s.length() == 0 || s.length() >= 4) return false;
            for(char c : s.toCharArray()){
                if(c < '0' || c > '9') return false;
            }
            if(s.charAt(0) == '0' && s.length() > 1) return false;
            if(Integer.valueOf(s) > 255) return false;
        }
        return true;
    }
    public boolean isValidIPv6(String IP){
        String[] input = IP.split(":");
        if(input.length != 8 || IP.charAt(IP.length() - 1) == ':') return false;
        for(String s : input){
            if(s.length() == 0 || s.length() > 4) return false;
            for(char c : s.toCharArray()){
                //0-9 A-F a-f
                if((c - '0' >= 0 && c - '9' <= 0) || (c - 'a' >= 0 && c - 'f' <= 0) || (c - 'A' >= 0 && c - 'F' <= 0)) continue;
                return false;
            }
        }
        return true;
    }


Problem solution in C++.

string validIPAddress(string IP) {
        stringstream ss(IP);
        string       item;
        char         ipv4Delim = '.';
        char         ipv6Delim = ':';
        
        if (count(begin(IP), end(IP), ipv4Delim) == 3){  // 3 dot's in ip v4
            while(getline(ss, item, ipv4Delim)){
                 for (auto d:item) if (!isdigit(d)) return "Neither"; 
                 if (item.empty() || item.length() > 3)                  return "Neither"; // checking empty
                 auto val = std::stoi(item);                           
                 if (to_string(val).length() != item.length() || val > 255 || val < 0 ) return "Neither";
            }
            return IP.back() == '.' ? "Neither":"IPv4";
        }
        else if (count(begin(IP), end(IP), ipv6Delim) == 7){ // 7 ":" in ipv6
             while(getline(ss, item, ipv6Delim)){
                 for (auto d:item) if (!isxdigit(d)) return "Neither";
                 if ( item.empty() || item.size() > 4)  return "Neither"; 
                auto hex_val = std::stoi(item, nullptr, 16);
            }
            return IP.back() == ':' ? "Neither":"IPv6";
        }
        
        return "Neither";
    }


Problem solution in C.

#include <stdio.h>
#include <ctype.h>
char* IPv4 = "IPv4";
char* IPv6 = "IPv6";
char* None = "Neither";
char* validIPv4(char* IP) {
    int cnt = 0; printf("ipv4\n");
    while(*IP) {
        printf("enter: %c\n", *IP);  
        if(!isdigit(*IP) || (*IP == '0' && IP[1] != '.')){
            return None;
        }
        int val = 0; cnt++; int scnt = 0;
        while(isdigit(*IP)) {
            scnt++;
            val = val*10 + (int)(*IP++%'0');
        }
        if(scnt > 3) {
            return None;
        }        
        if(*IP != '.' || val > 255)
            return (*IP || cnt != 3) ? None : IPv4;
        IP++;
    }
    return None;
}

char* validIPv6(char* IP) {
    int cnt = 0;
    while(*IP) {  
        int val = 0; cnt++; int scnt = 0;
        printf("enter: %c\n", *IP);        
        if(*IP == ':') {
            return None;
        }        
        while(isxdigit(*IP)) {
            scnt++;
            val = val*10;
            val += (*IP >= '0' && *IP <= '9') ? *IP%'0' : tolower(*IP)%'a'+10;
            IP++;
        }        
        if(scnt > 4) {
            return None;
        }
        if(*IP != ':' || val > 65535) {
            printf("%d %d %c\n", cnt, val, *IP);
            return (cnt != 7 || *IP != 0) ? None : IPv6;
        }

        IP++;
    }
    return None;
}

char* validIPAddress(char* IP) {
    IPv4 = "IPv4";
    IPv6 = "IPv6"; 
    if(*IP == '0')
        return None;
    int val = 0; int scnt = 0;
    while(isxdigit(*IP)) {
        if(!isdigit(*IP))
            IPv4 = IPv6;
        scnt++;
        val = val*10 + (*IP >= '0' && *IP <= '9') ? *IP%'0' : tolower(*IP)%'a'+10; IP++;
    }

    if(*IP == '.' && val <= 255 && IPv6 != IPv4 && scnt < 4)
        return validIPv4(++IP);
    else
    if (*IP == ':' && val <= 65535 && scnt < 5)
        return validIPv6(++IP);

    return None;
}