Last Updated: 18 Dec, 2020

Program to validate IP address

Easy
Asked in companies
OlaAmazonPhonePe

Problem statement

You are given the text ‘IPAddress’. Your task is to check if the given text ‘IPAddress’ is a valid ‘IPv4’ or not.

Conditions for a valid ‘IPv4’ are:

1. Text form of ‘IPAddress’ must be ‘a.b.c.d’
2. The values of a,b,c and d can vary from ‘0’ to ‘255’ and both ‘0’ and ‘255’ are inclusive.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The next ‘T’ lines represent the ‘T’ test cases.

The first and only line of every test case contains a string ‘IPAddress’.
Output Format:
For each test case, print ‘True’ if the given text ‘IPAddress’ is valid ‘IPv4’ else print ‘False’.
Note:
You don’t have to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^4
1 <= length of given text <= 50

Time limit: 1 sec

Approaches

01 Approach

Idea is that, check every chunk is valid or not and the number of chunks is 4.

 

  • Suppose given ‘IPAddress’ in form of ‘a.b.c.d’.
  • Then first check for ‘a’ part that ‘a’ is valid ‘IPv4’ chunk or not, if ‘a’ part is valid then recursively check if the form remains part ‘b.c.d’.
  • Call ‘isValidChunk(chunk)’ its return given chunk is valid or not means if given ‘chunk’ is a string and its integer conversion is ‘0’ to ‘255’ then returns ‘True’ else ‘False’.
  • Call ‘helperMethod(IPAddress)’ which will return a number of chunks in ‘IPAddress’ of all chunks are valid otherwise its returns‘ -1’.
  • If the given ‘IPAddress’ has a total ‘4’ chunk then it's a valid ‘IPv4’, so return ‘True’.
  • If given ‘IPAddress’ has no ‘4’ chunks, return ‘False’

02 Approach

If a given text ‘IPAddress’ has exactly three dots any every two continuous dots containing a number from ‘0’ to ‘255’ then ‘IPAddress’ is valid.

 

  • Keep two variables ‘dot=0’ and ‘currentNumber=-1’, Iterate the whole text ‘IPAddress’ with the help of a loop with index ‘i’.
  • If any point of time, “IPAddress[i] ==’.’”
    • Check ‘currentNumber’ is between ‘0’ to ‘255’. If yes then update the value of ‘dot = dot+1’ and  ‘currentNumber=-1’, else return ‘False’ because it is not holding the condition that every chunk from ‘0’ to ‘255’.
    • Now the question is how to update ‘currentNumber’
      • If ‘currentNumber’ is ‘x’ and ‘IPAddress[i]’ is y then update ‘currentNumber= x*10+y’
      • If ‘currentNUmber’ is ‘-1’ then update is with ‘currentNumber= IPAddress[i]’.
  • Every single character ‘IPAddress[i]’ must be ‘0’ to ‘9’ and ‘.’.
  • After the iterating whole text ‘IPAddress’ string check
    • If ‘dot==3’ then return ‘True’.
    • Else return ‘False’.
  • We are using ‘currentNumber = -1’ because if we use ‘currentNumber’ value is ‘0’ and at any time two dots are consecutive then ‘currentNumber’ will be ‘0’ and it is a part of the range ‘0’ to ‘255’.