Open In App

Check if the given string is IPv4 or IPv6 or Invalid

Improve
Improve
Like Article
Like
Save
Share
Report

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;
}


Java




// Java program for the above approach
import java.util.*;
 
public class Main {
    // Function to check if the given string
    // S is IPv4 or not
    public static boolean 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.length(); i++) {
            if (s.charAt(i) == '.') {
                cnt++;
            }
        }
        // Not a valid IP address
        if (cnt != 3) {
            return false;
        }
        // Stores the tokens
        ArrayList<String> tokens = new ArrayList<String>();
        // StringTokenizer class check1
        StringTokenizer check1
            = new StringTokenizer(s, ".");
        // Tokenizing w.r.t. '.'
        while (check1.hasMoreTokens()) {
            tokens.add(check1.nextToken());
        }
        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.get(i).equals("0")) {
                continue;
            }
            if (tokens.get(i).length() == 0) {
                return false;
            }
            for (int j = 0; j < tokens.get(i).length();
                 j++) {
                if (tokens.get(i).charAt(j) > '9'
                    || tokens.get(i).charAt(j) < '0') {
                    return false;
                }
                num *= 10;
                num += tokens.get(i).charAt(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
    public static boolean checkHex(String s)
    {
        // Size of string s
        int n = s.length();
        // Iterate over string
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(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
    public static boolean checkIPv6(String s)
    {
        // Store the count of occurrence
        // of ':' in the given string
        int cnt = 0;
 
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ':') {
                cnt++;
            }
        }
 
        // Not a valid IP Address
        if (cnt != 7) {
            return false;
        }
 
        // Stores the tokens
        ArrayList<String> tokens = new ArrayList<String>();
 
        // StringTokenizer class check1
        StringTokenizer check1
            = new StringTokenizer(s, ":");
        // Tokenizing w.r.t. ':'
        while (check1.hasMoreTokens()) {
            tokens.add(check1.nextToken());
        }
 
        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.get(i).length();
            if (!checkHex(tokens.get(i)) || len > 4
                || len < 1)
                return false;
        }
        return true;
    }
    // Function to check if the string
    // S is IPv4 or IPv6 or Invalid
    public static void checkIPAddress(String s)
    {
        // Check if the string is IPv4
        if (checkIPv4(s))
            System.out.println("IPv4");
 
        // Check if the string is IPv6
        else if (checkIPv6(s))
            System.out.println("IPv6");
 
        // Otherwise, print "Invalid"
        else
            System.out.println("Invalid");
    }
    public static void main(String args[])
    {
        String s = "192.168.0.1";
        checkIPAddress(s);
    }
}


Python3




# Python program for the above approach
import re
 
# Function to check if the given string
# S is IPv4 or not
def checkIPv4(s):
    # Count the occurrence of '.' in the given string
    cnt = s.count('.')
 
    # Not a valid IP address
    if cnt != 3:
        return False
 
    # Split the string into tokens
    tokens = s.split('.')
 
    if len(tokens) != 4:
        return False
 
    # Check if all the tokenized strings
    # lie in the range [0, 255]
    for token in tokens:
        # Base Case
        if token == "0":
            continue
 
        if len(token) == 0:
            return False
 
        # Check if the tokenized string is a number
        if not token.isdigit():
            return False
 
        # Range check for the number
        if int(token) > 255 or int(token) < 0:
            return False
 
    return True
 
 
# Function to check if the string
# represents a hexadecimal number
def checkHex(s):
    # Check if the string is a valid hexadecimal number
    return bool(re.match(r'^[0-9a-fA-F]+$', s))
 
 
# Function to check if the given
# string S is IPv6 or not
def checkIPv6(s):
    # Count the occurrence of ':' in the given string
    cnt = s.count(':')
 
    # Not a valid IP Address
    if cnt != 7:
        return False
 
    # Split the string into tokens
    tokens = s.split(':')
 
    if len(tokens) != 8:
        return False
 
    # Check if all the tokenized strings
    # are in hexadecimal format
    for token in tokens:
        # Check if the tokenized string is a valid hexadecimal number
        if not checkHex(token) or len(token) > 4 or len(token) < 1:
            return False
 
    return True
 
 
# Function to check if the string
# S is IPv4 or IPv6 or Invalid
def checkIPAddress(s):
    # Check if the string is IPv4
    if checkIPv4(s):
        print("IPv4")
 
    # Check if the string is IPv6
    elif checkIPv6(s):
        print("IPv6")
 
    # Otherwise, print "Invalid"
    else:
        print("Invalid")
 
 
# Driver Code
S = "192.168.0.1"
checkIPAddress(S)
 
# Contributed by adityashae15


Javascript




// Function to check if the given string
// S is IPv4 or not
function checkIPv4(s) {
  // Count the occurrence of '.' in the given string
  let cnt = s.split('.').length - 1;
 
  // Not a valid IP address
  if (cnt !== 3) {
    return false;
  }
 
  // Split the string into tokens
  let tokens = s.split('.');
 
  if (tokens.length !== 4) {
    return false;
  }
 
  // Check if all the tokenized strings
  // lie in the range [0, 255]
  for (let token of tokens) {
    // Base Case
    if (token === "0") {
      continue;
    }
 
    if (token.length === 0) {
      return false;
    }
 
    // Check if the tokenized string is a number
    if (!/^\d+$/.test(token)) {
      return false;
    }
 
    // Range check for the number
    if (parseInt(token) > 255 || parseInt(token) < 0) {
      return false;
    }
  }
 
  return true;
}
 
 
// Function to check if the string
// represents a hexadecimal number
function checkHex(s) {
  // Check if the string is a valid hexadecimal number
  return /^[0-9a-fA-F]+$/.test(s);
}
 
 
// Function to check if the given
// string S is IPv6 or not
function checkIPv6(s) {
  // Count the occurrence of ':' in the given string
  let cnt = s.split(':').length - 1;
 
  // Not a valid IP Address
  if (cnt !== 7) {
    return false;
  }
 
  // Split the string into tokens
  let tokens = s.split(':');
 
  if (tokens.length !== 8) {
    return false;
  }
 
  // Check if all the tokenized strings
  // are in hexadecimal format
  for (let token of tokens) {
    // Check if the tokenized string is a valid hexadecimal number
    if (!checkHex(token) || token.length > 4 || token.length < 1) {
      return false;
    }
  }
 
  return true;
}
 
 
// Function to check if the string
// S is IPv4 or IPv6 or Invalid
function checkIPAddress(s) {
  // Check if the string is IPv4
  if (checkIPv4(s)) {
    console.log("IPv4");
  }
 
  // Check if the string is IPv6
  else if (checkIPv6(s)) {
    console.log("IPv6");
  }
 
  // Otherwise, print "Invalid"
  else {
    console.log("Invalid");
  }
}
 
 
// Driver Code
let S = "192.168.0.1";
checkIPAddress(S);


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class MainClass {
    public static 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.Length; i++) {
            if (s[i] == '.') {
                cnt++;
            }
        }
        // Not a valid IP address
        if (cnt != 3) {
            return false;
        }
        // Stores the tokens
        List<string> tokens = new List<string>();
        // Split the string w.r.t. '.'
        string[] split = s.Split('.');
        foreach(string token in split)
        {
            tokens.Add(token);
        }
        if (tokens.Count != 4) {
            return false;
        }
 
        // Check if all the tokenized strings lies in the
        // range [0, 255]
        foreach(string token in tokens)
        {
            int num = 0;
            // Base Case
            if (token.Equals("0")) {
                continue;
            }
            if (token.Length == 0) {
                return false;
            }
            foreach(char c in token)
            {
                if (c > '9' || c < '0') {
                    return false;
                }
                num *= 10;
                num += c - '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
    public static 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
    public static bool checkIPv6(string s)
    {
 
        // Store the count of occurrence
        // of ':' in the given string
        int cnt = 0;
 
        for (int i = 0; i < s.Length; i++) {
            if (s[i] == ':') {
                cnt++;
            }
        }
 
        // Not a valid IP Address
        if (cnt != 7) {
            return false;
        }
 
        // Stores the tokens
        List<string> tokens = new List<string>();
 
        // Split the string w.r.t. ':'
        string[] split = s.Split(':');
        foreach(string token in split)
        {
            tokens.Add(token);
        }
 
        if (tokens.Count != 8) {
            return false;
        }
 
        // Check if all the tokenized strings are in
        // hexadecimal format
        foreach(string token in tokens)
        {
            int len = token.Length;
            if (!checkHex(token) || len > 4 || len < 1)
                return false;
        }
        return true;
    }
 
    // Function to check if the string
    // S is IPv4 or IPv6 or Invalid
    public static void checkIPAddress(string s)
    {
        // Check if the string is IPv4
        if (checkIPv4(s))
            Console.WriteLine("IPv4");
 
        // Check if the string is IPv6
        else if (checkIPv6(s))
            Console.WriteLine("IPv6");
 
        // Otherwise, print "Invalid"
        else
            Console.WriteLine("Invalid");
    }
    public static void Main(string[] args)
    {
        string s = "192.168.0.1";
        checkIPAddress(s);
    }
}


Output:

IPv4

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



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads