Validate an IP address using Python without using RegEx
Last Updated :
31 Jul, 2023
Given an IP address as input, the task is to write a Python program to check whether the given IP Address is Valid or not without using RegEx.
What is an IP (Internet Protocol) Address?
Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255).
Examples:
Input: 192.168.0.1
Output: Valid IP address
Input: 110.234.52.124
Output: Valid IP address
Input: 666.1.2.2
Output: Invalid IP address
Validate an IP address using Python without using RegEx
Method #1: Checking the number of periods using count() method and then the range of numbers between each period.
Python3
def isValidIP(s):
if s.count( '.' ) ! = 3 :
return 'Invalid Ip address'
l = list ( map ( str , s.split( '.' )))
for ele in l:
if int (ele) < 0 or int (ele) > 255 or (ele[ 0 ] = = '0' and len (ele)! = 1 ):
return 'Invalid Ip address'
return 'Valid Ip address'
print (isValidIP( '666.1.2.2' ))
|
Output
Invalid Ip address
Method #2: Using a variable to check the number of periods and using a set to check if the range of numbers between periods is between 0 and 255(inclusive).
Python3
def isValidIP(s):
counter = 0
for i in range ( 0 , len (s)):
if (s[i] = = '.' ):
counter = counter + 1
if (counter ! = 3 ):
return 0
st = set ()
for i in range ( 0 , 256 ):
st.add( str (i))
counter = 0
temp = ""
for i in range ( 0 , len (s)):
if (s[i] ! = '.' ):
temp = temp + s[i]
else :
if (temp in st):
counter = counter + 1
temp = ""
if (temp in st):
counter = counter + 1
if (counter = = 4 ):
return 'Valid Ip address'
else :
return 'Invalid Ip address'
print (isValidIP( '110.234.52.124' ))
|
Please Login to comment...