Check if a string is a valid IP address or not in Python by the naive approach

In this post, we are going to see how we can validate that a given string is a valid IP address(IPv4) or not in Python. This post will be helpful for beginners as we will accomplish the task using simple Python in-built functions such as given below:

split(separator) –
Called upon a string and returns an array of string elements; which are separated by the passed separator (if not, then it takes whitespace as a separator by default).
isnumeric(string_argument) – Returns True if a string contains all numeric characters, else false.

Python program to check if a string is a valid IP address or not

Firstly let’s know what a valid IP address looks like.

  1. The IP address should be of the format (X.X.X.X)
  2. Each represents a number within an inclusive range of 0 to 255.
  3. Examples:- 12.192.168.32 , 0.0.0.64 , 255.255.192.254 , etc.
    Valid IP

We will start our code by accepting the input and assigning the flag to false, which will make the tracking of conditions handy.

string = input()
flag = False

Now before splitting the string, we will first check whether it contains (.). This step will save us time from processing the wrong input.
Then we will use the split() function with “.” as separator argument and get the list of elements.

if ("." in string):
    elements_array = string.split(".")

Further continuing with our task, now we will check whether we got exactly four elements or not. For this, we will validate the length of the elements_array equal to 4 with the help of len() function.
After validating we will iterate the elements_array using for loop.

if(len(elements_array) == 4):
        for i in elements_array:

Now, for each iteration we will check for 2 things:-
1) The element should consist of numeric characters only. We will implement this with the help of the isnumeric() function.
2) The numeric value of the element lies in the inclusive range of 0 to 255.

for i in elements_array:
    if (i.isnumeric() and int(i)>=0 and int(i)<=255):
        flag=True
    else:
        flag=False
        break

So, for each valid iteration, we are setting the value of the flag to true. In case of invalid, the loop will terminate after setting the value of the flag to false.

Once the iteration is completed or terminated we check the status of the flag and print the result corresponding to it.
Let’s see the complete code,

string = input()
flag = False
if ("." in string):
    elements_array = string.strip().split(".")
    if(len(elements_array) == 4):
        for i in elements_array:
            if (i.isnumeric() and int(i)>=0 and int(i)<=255):
                flag=True
            else:
                flag=False
                break
if flag:
    print("Valid")
else:
    print("Invalid")

OUTPUT:

123.234.168.0
Valid
123.264.168.0
Inalid
A.234.168.0
Invalid
0.255.254.0
Valid
123...
Invalid

Leave a Reply

Your email address will not be published. Required fields are marked *