Check if the given string is IPv4 or IPv6 or Invalid - GeeksforGeeks

18 Jun, 2021
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: IPv4Explanation: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 notbool 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 numberbool 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 notbool 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 Invalidvoid 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 Codeint main(){    string S = "192.168.0.1";    checkIPAddress(S);    return 0;}
IPv4

Time Complexity: O(N)Auxiliary Space: O(N)
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Print all subsequences of a string
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching