Articles by FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
Articles by FavTutor
No Result
View All Result
Home Data Structures and Algorithms

Validate IP Address Problem ( C++, JAVA, Python)

Mansi Agarwal by Mansi Agarwal
April 3, 2025
Reading Time: 8 mins read
validate ip address
Follow us on Google News   Subscribe to our newsletter

An IP address is used to transfer the information to computers connected through the internet. Each computer connected via the internet has a unique IP address. Every computer connected via the same Internet has a unique IP address. In this article, we will discuss the problem “Validate IP Address”. It is based on the IP address. This question was recently asked in the “Deutsche Bank” coding round. 

What is the “Validate IP Address” Problem?

IP addresses are of two types. IPV4 and IPV6. In this problem, you are given a string. You have to determine whether it is IPV4 or IPV6. 

An IPV4 address is in the form of a1.a2.a3.a4. Where (0<=ai<=255), here i goes from 1 to 4. This means each a1, a2, a3, and a4 lies between 0 to 255.

Also, ai should not have leading zeroes. For example, 23.2.10.244 is a valid IPV4 address, while 23.2.10, 23.2.10., 265.10.2.5, and 23.02.10.244 are not valid IPV4 addresses.

An IPV6 address is in the form of a1:a2:a3:a4:a5:a6:a7:a8. Where size of 1<=ai<=4 here i goes from 1 to 8. Each character of ai can be ‘0’ to ‘9’, ‘a’ to ‘f’, or ‘A’ to ‘F’.

In an IPV6 address, ai can have leading zeroes. For example, a234:F:23:b2:08:00:aC:ee is a valid IPV6 address, but a2671:1F:23:b2:08:00:aC:ee, g2:1F:23:b2:0988:00:aC:ee, a2:1F:23:b2:08:00:aC, and a2::23:b2:08:00:aC:ee is not a valid IPV6 address.

Solution to IP Address Problem

This is a basic string question in which we just need to check all the conditions given in the question. Once we had checked all the conditions, we could easily determine if it was an IPV4, IPV6, or none of them.

Let’s examine this approach step by step.

IPV4 check

  • First, create an empty string temp that stores ai, and an integer variable count that stores a count of ai.
  • Now iterate over the string and check if s[i] is ‘.’ or not. 
  • If it is not ‘.’ then check if s[i] lies between ‘0’ to ‘9’ or not. If it does not lie between them, return false. Otherwise, check if the size of the temp exceeds 3 or not. If it exceeds 3, return false.
  • If s[i] is equal to ‘.’ then increment the count by 1. Now check if the size of temp is zero and return false. Now convert this temp into an integer and check if the integer lies between 0 to 255 if not, return false. Also, check that if the size of temp is greater than 1 and temp[0] is 0, return false. At last, check if it is greater than or equal to 4 and return false. After checking all the conditions make temp = “”.

IPV6 check

  • First, create an empty string temp that stores ai, and an integer variable count that stores a count of ai.
  • Now iterate over the string and check if s[i] is ‘:’ or not. 
  • If it is not ‘.’ then check if s[i] lies between ‘0’ to ‘9’, ‘a’ to ‘f’, or ‘A’ to ‘F’ or not. If it does not lie between them, return false. Otherwise, check if the size of the temp exceeds 4 or not. If it exceeds 4, return false.
  • If s[i] is equal to ‘:’ then increment the count by 1. Now check if the size of the temp is zero, or the temp size is greater than 4, or the count is greater than 8, and return false. Once you have checked all the conditions, assign temp = “”.
  • After the loop is over, check for the temperature as we had checked in point 4.
  • At last return true.

In the main function, check if IPV4 returns true, then return “IPV4”. If not, check if IPV6 returns true, then return “IPV6”. If not, then return “Neither”.

Let’s examine the code for the above approach.

C++ Code

Here is the C++ solution:

#include<bits/stdc++.h>

using namespace std;

    bool check_IPv4(string s){

        vector<int>v;

        string temp = "";

        int ct = 0;

        for(int i=0;i< s.size(); i++){

            if(s[i] == '.'){

                ct++;

                if(temp.size() == 0) return false;

                int a = stoi(temp);

                if(a>255 || ct>=4) return false;

                if(temp.size()>1 && temp[0]=='0')return false;

                temp = "";

            }else{

                int ch = s[i] - '0';

                // cout<<temp.size();

                if(ch>=0 && ch<= 9) temp += s[i];

                else return false;

                if(temp.size() > 3) return false;

            }

        }

        ct++;

        if(temp.size() == 0) return false;

        int a = stoi(temp);

        if(a>255) return false;

        if((temp.size()>1 && temp[0]=='0') || (ct!=4))return false;

        return true;

    }

    bool check_Ipv6(string& s){

        string t = "";

        int ct = 0;

        for(int i=0;i<s.size();i++){

            if((s[i]>='0' && s[i]<='9') || (s[i]>='a' && s[i]<='f') || (s[i]>='A' && s[i]<='F')){

                if(t.size()>4) return false;

                t+=s[i];

            }else if(s[i]==':'){

                ct++;

                if(t.size()==0 || t.size()>4 || ct>=8) return false;

                t="";

            }else return false; 

        }

        ct++;

        if(t.size()==0 || t.size()>4 || ct!=8) return false;

        return true;

    }

int main(){

    string s = "Fa:ab:0132:21:a1:01:100C:1234";

    if(check_IPv4(s)) {

        cout<<"IPv4"<<endl;

        return 0;

    }

    if(check_Ipv6(s)) {

        cout<<"IPv6"<<endl;

        return 0;

    }

    cout<<"Neither";

    return 0;

}

Java Code

Here is the same solution in Java:

import java.util.*;

class IPAddressChecker {

    public static boolean checkIPv4(String s) {

        List<Integer> v = new ArrayList<>();

        StringBuilder temp = new StringBuilder();

        int ct = 0;

        for (int i = 0; i < s.length(); i++) {

            if (s.charAt(i) == '.') {

                ct++;

                if (temp.length() == 0) return false;

                int a = Integer.parseInt(temp.toString());

                if (a > 255 || ct >= 4) return false;

                if (temp.length() > 1 && temp.charAt(0) == '0') return false;

                temp.setLength(0);

            } else {

                int ch = s.charAt(i) - '0';

                if (ch >= 0 && ch <= 9) temp.append(s.charAt(i));

                else return false;

                if (temp.length() > 3) return false;

            }

        }

        ct++;

        if (temp.length() == 0) return false;

        int a = Integer.parseInt(temp.toString());

        if (a > 255) return false;

        if ((temp.length() > 1 && temp.charAt(0) == '0') || (ct != 4)) return false;

        return true;

    }

    public static boolean checkIPv6(String s) {

        StringBuilder t = new StringBuilder();

        int ct = 0;

        for (int i = 0; i < s.length(); i++) {

            if ((s.charAt(i) >= '0' && s.charAt(i) <= '9') || 

                (s.charAt(i) >= 'a' && s.charAt(i) <= 'f') || 

                (s.charAt(i) >= 'A' && s.charAt(i) <= 'F')) {

                if (t.length() > 4) return false;

                t.append(s.charAt(i));

            } else if (s.charAt(i) == ':') {

                ct++;

                if (t.length() == 0 || t.length() > 4 || ct >= 8) return false;

                t.setLength(0);

            } else return false; 

        }

        ct++;

        if (t.length() == 0 || t.length() > 4 || ct != 8) return false;

        return true;

    }

    public static void main(String[] args) {

        String s = "Fa:ab:0132:21:a1:01:100C:1234";

        if (checkIPv4(s)) {

            System.out.println("IPv4");

            return;

        }

        if (checkIPv6(s)) {

            System.out.println("IPv6");

            return;

        }

        System.out.println("Neither");

    }

}

Python Code

You can implement it in Python too:

def check_ipv4(s):

    v = []

    temp = ""

    ct = 0

    for i in range(len(s)):

        if s[i] == '.':

            ct += 1

            if len(temp) == 0:

                return False

            a = int(temp)

            if a > 255 or ct >= 4:

                return False

            if len(temp) > 1 and temp[0] == '0':

                return False

            temp = ""

        else:

            ch = ord(s[i]) - ord('0')

            if 0 <= ch <= 9:

                temp += s[i]

            else:

                return False

            if len(temp) > 3:

                return False

    ct += 1

    if len(temp) == 0:

        return False

    a = int(temp)

    if a > 255:

        return False

    if (len(temp) > 1 and temp[0] == '0') or (ct != 4):

        return False

    return True

def check_ipv6(s):

    t = ""

    ct = 0

    for i in range(len(s)):

        if '0' <= s[i] <= '9' or 'a' <= s[i] <= 'f' or 'A' <= s[i] <= 'F':

            if len(t) > 4:

                return False

            t += s[i]

        elif s[i] == ':':

            ct += 1

            if len(t) == 0 or len(t) > 4 or ct >= 8:

                return False

            t = ""

        else:

            return False

    ct += 1

    if len(t) == 0 or len(t) > 4 or ct != 8:

        return False

    return True

s = "Fa:ab:0132:21:a1:01:100C:1234"

if check_ipv4(s):

    print("IPv4")

elif check_ipv6(s):

    print("IPv6")

else:

    print("Neither")

Output: 

IPv6

Complexity Analysis

The time complexity for the above approach is O(n), where n is the size of the string. We are just iterating the string twice, whose time complexity is O(2*n) ~ O(n). The space complexity of the above code is O(1,) as we are not using any extra space.

Conclusion

So, we have discussed how to solve the problem “Validate IP Address”. We have seen that it’s an easy string question; all we have to check are all the conditions that are given in the question. As it has many conditions to check one can easily miss out. Try to solve some more questions like “IP to CIDR” and “Strong Password Checker II”. Try to solve these questions on your own. 

ShareTweetShareSendSend
Mansi Agarwal

Mansi Agarwal

I am Mansi Agarwal, a final-year student at IIT BHU. I am very keen on competitive programming, with my primary area of interest being Data Structures & Algorithms. I have solved over 1000 LeetCode problems.

RelatedPosts

Shortest Palindrome Problem

Shortest Palindrome Problem ( C++, JAVA, Python)

April 4, 2025
Zigzag Conversion Problem

Zigzag Conversion Problem (C++, Java, Python)

April 4, 2025
Next Right Pointers In Each Node

Populating Next Right Pointers In Each Node (with code)

March 27, 2024
Coin Change II

Coin Change II Problem (C++, Java, Python)

April 7, 2025
Minimum Size Subarray Sum

Minimum Size Subarray Sum Problem (C++, Java, Python)

April 7, 2025

About FavTutor

FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.

Categories

  • AI News, Research & Latest Updates
  • Trending
  • Data Structures
  • Web Developement
  • Data Science

Important Subjects

  • Python Assignment Help
  • C++ Help
  • R Programming Help
  • Java Homework Help
  • Programming Help

Resources

  • About Us
  • Contact Us
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.

No Result
View All Result
  • AI News
  • Data Structures
  • Web Developement
  • AI Code Generator
  • Student Help
  • Main Website

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.