Paste: IP4444

Author: sss
Mode: c++
Date: Fri, 26 Aug 2022 04:17:36
Plain Text |
string validIP4(string IP) {
        int i = 0, j = 0, count_dot = 0, count_num = 0, num;
        //count_dots to maintain the number of dots encountered
        //count_num to maintain the number of numbers encountered between the dots
        
        while(i<IP.size()) {
            num = 0;
            
            //Inner while loop runs from the beginning of first digit to the next dot
            while(j<IP.size() && IP[j] != '.') {
                //If a character other than a digit is found, return "Neither"
                if(IP[j] < 48 || IP[j] > 57)
                    return "Neither";
                
                //Covert the character digit to the number
                num = (num * 10) + IP[j] - '0';
                
                //If number if greater than 255, return "Neither" to avoid overflow
                if(num > 255)
                    return "Neither";
                
                //If number consists of a leading zero, return "Neither"
                if(j != i && num < 10)
                    return "Neither";
                
                j++;
            }
            
            //Count the number of numbers between the dots
            //If clause can be removed I guess. Do try it and post a comment
            if(num > 255)
                return "Neither";
            
            else 
                count_num++;
            
            //If the next character is a dot, increment the dot counter
            if(IP[j] && IP[j] == '.') {
                count_dot++;
                j++;
                
                //After incrementing the pointer, if a dot is found, it is invalid
                //Example: XX.XXXX..X
                if(IP[j] == '.')
                    return "Neither";
            }
            
            i = j;
        }
        
        //If there are 3 dots and 4 numbers, return IPv4 else return "Neither"
        if(count_dot != 3 || count_num != 4)
            return "Neither";
        
        return "IPv4";
    }




string validIPAddress(string queryIP) {
        bool ipv4 = false, ipv6 = false;
        
        //Check if the IP contains only dots or only colons
        for(int i=0; i<queryIP.size(); i++) {
            if(queryIP[i] == '.')
                ipv4 = true;
            
            else if(queryIP[i] == ':')
                ipv6 = true;
        }
        
        //Return "Neither" if dot and colon both exist
        if(ipv4 && ipv6)
            return "Neither";
        
        //Check and return if only dots are present
        if(ipv4)
            return validIP4(queryIP);
        
        //Check and return if only colons are present
        return validIP6(queryIP);
    }

New Annotation

Summary:
Author:
Mode:
Body: