Skip to content
Related Articles

Related Articles

Improve Article

Check if the given string is IPv4 or IPv6 or Invalid

  • Difficulty Level : Medium
  • Last Updated : 18 Jun, 2021
Geek Week

Given a string S consisting of N characters, the task is to check if the given string S is IPv4 or IPv6 or Invalid. If the given string S is a valid IPv4, then print “IPv4”, if the string S is a valid IPv6, then print “IPv4”. Otherwise, print “-1”.

A valid IPv4 address is an IP in the form “x1.x2.x3.x4” where 0 ≤ xi ≤ 255 and xi cannot contain leading zeros.

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.

Examples:

Input: S = “192.168.0.1”
Output: IPv4
Explanation:
The given string S is a valid IPv4 address as it is of the form “x1.x2.x3.x4” where 0 ≤ xi ≤ 255.



Input: S = “2001:0db8:85a3:0000:0000:8a2e:0370:7334”
Output: IPv6

Approach: The given problem can be solved by splitting the string with respect to ‘.’ while checking for IPv4 address and ‘:’ while checking for IPv6 address and check for the conditions for the string as IPv4 or IPv6 or Invalid.

Follow the steps below to check if the string is IPv4:

  • Initialize a boolean variable, ans as true to check if the string is IPv4 or not.
  • Store the count of occurrence of ‘.’ in the given string, S in a variable cnt.
  • If the value of cnt is not equal to 3, then update the value of ans to false. Otherwise, tokenize the string, S with respect to the character ‘.’ and store the tokenized strings in an array V.
  • Check if the size of V is equal to 4 or not. If not equal, update the value of ans to false.
  • Otherwise, traverse the array, V and for each string, str in V check it lies in the range [0, 255] and does not contain leading 0s. If not, then update the value of ans to false.
  • If the value of ans is true, then the string is a valid IPv4 address, Otherwise, it is not a valid IPv4 address.

Follow the steps below to check if the string is IPv6:

  • Initialize a boolean variable, ans as true to check if the string is IPv6 or not.
  • Store the count of occurrence of ‘:’ in the given string, S in a variable cnt.
  • If the value of cnt is not equal to 7, then update ans to false. Otherwise, tokenize the string, S w.r.t character ‘:’ and store the tokenized strings in an array, V.
  • Check if the size of V is equal to 8 or not. If not equal, update ans to false.
  • Otherwise, traverse the array, V and for each string, str in V check its length is in the range [1, 4] and it is a valid hexadecimal number. If not, then update the value of ans to false.
  • If the value of ans is true, then the string is a valid IPv6 address. Otherwise, it is not a valid IPv6 address.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if the given string
// S is IPv4 or not
bool checkIPv4(string s)
{
    // Store the count of occurrence
    // of '.' in the given string
    int cnt = 0;
  
    // Traverse the string s
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '.')
            cnt++;
    }
  
    // Not a valid IP address
    if (cnt != 3)
        return false;
  
    // Stores the tokens
    vector<string> tokens;
  
    // stringstream class check1
    stringstream check1(s);
    string intermediate;
  
    // Tokenizing w.r.t. '.'
    while (getline(check1,
                   intermediate, '.')) {
        tokens.push_back(intermediate);
    }
  
    if (tokens.size() != 4)
        return false;
  
    // Check if all the tokenized strings
    // lies in the range [0, 255]
    for (int i = 0; i < tokens.size(); i++) {
        int num = 0;
  
        // Base Case
        if (tokens[i] == "0")
            continue;
  
        if (tokens[i].size() == 0)
            return false;
  
        for (int j = 0;
             j < tokens[i].size();
             j++) {
            if (tokens[i][j] > '9'
                || tokens[i][j] < '0')
                return false;
  
            num *= 10;
            num += tokens[i][j] - '0';
  
            if (num == 0)
                return false;
        }
  
        // Range check for num
        if (num > 255 || num < 0)
            return false;
    }
  
    return true;
}
  
// Function to check if the string
// represents a hexadecimal number
bool checkHex(string s)
{
    // Size of string s
    int n = s.length();
  
    // Iterate over string
    for (int i = 0; i < n; i++) {
        char ch = s[i];
  
        // Check if the character
        // is invalid
        if ((ch < '0' || ch > '9')
            && (ch < 'A' || ch > 'F')
            && (ch < 'a' || ch > 'f')) {
            return false;
        }
    }
  
    return true;
}
  
// Function to check if the given
// string S is IPv6 or not
bool checkIPv6(string s)
{
    // Store the count of occurrence
    // of ':' in the given string
    int cnt = 0;
  
    for (int i = 0; i < s.size();
         i++) {
        if (s[i] == ':')
            cnt++;
    }
  
    // Not a valid IP Address
    if (cnt != 7)
        return false;
  
    // Stores the tokens
    vector<string> tokens;
  
    // stringstream class check1
    stringstream check1(s);
    string intermediate;
  
    // Tokenizing w.r.t. ':'
    while (getline(
        check1,
        intermediate, ':')) {
        tokens.push_back(intermediate);
    }
  
    if (tokens.size() != 8)
        return false;
  
    // Check if all the tokenized strings
    // are in hexadecimal format
    for (int i = 0;
         i < tokens.size(); i++) {
  
        int len = tokens[i].size();
  
        if (!checkHex(tokens[i])
            || len > 4 || len < 1) {
            return false;
        }
    }
    return true;
}
  
// Function to check if the string
// S is IPv4 or IPv6 or Invalid
void checkIPAddress(string s)
{
    // Check if the string is IPv4
    if (checkIPv4(s))
        cout << "IPv4";
  
    // Check if the string is IPv6
    else if (checkIPv6(s))
        cout << "IPv6";
  
    // Otherwise, print "Invalid"
    else
        cout << "Invalid";
}
  
// Driver Code
int main()
{
    string S = "192.168.0.1";
    checkIPAddress(S);
    return 0;
}
Output:
IPv4

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :