;

How to Validate an IPv4 IP Address is Valid or Not using Python


Tutorialsrack 23/09/2020 Python

In this article, you will learn how to validate an IPv4 IP address is valid or not using Python. There are many ways to validate the IPv4 IP address using python.

Here are some examples to validate whether the IPv4 IP address is valid or not.

Example 1: Without Using Any Python Library

In this example, we are not using any python library to validate an IPv4 IP address is valid or not using python.

Here is the source of the code of the program to validate whether an IPv4 IP address is Valid or not.

Example 1: Without Using Any Python Library
# How to Validate an IPv4 IP Address is Valid or Not using Python
 
class Solution(object):
   def Isvalid_IPv4_IPAddress(self, IP):
 
      def isIPv4(s):
         try: return str(int(s)) == s and 0 <= int(s) <= 255
         except: return False
 
      if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
         return IP+" is a valid IPv4 IP Address"
      return IP+" is not a valid IPv4 IP Address"
 
ob = Solution()
print(ob.Isvalid_IPv4_IPAddress("172.16.254.1"))
print(ob.Isvalid_IPv4_IPAddress("172.16.1"))
print(ob.Isvalid_IPv4_IPAddress("5"))
print(ob.Isvalid_IPv4_IPAddress("172.16.254.266"))
Output

172.16.254.1 is a valid IPv4 IP Address

172.16.1 is not a valid IPv4 IP Address      

5 is not a valid IPv4 IP Address

172.16.254.266 is not a valid IPv4 IP Address

Example 2: Using socket Module

In this example, we used the built-in python socket module to validate the IPv4 IP address. And the Python function inet_pton() from the socket module converts an IP address in string format to a packed binary format.

Here is the source code of the program to validate an IPv4 IP address is Valid or Invalid.

Example 2: Using socket Module
# Import Module
import socket
 
def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return address.count('.') == 3
    except socket.error:  # not a valid address
        return False
    return True
 
print(is_valid_ipv4_address("123.52.72.55"))  # Output ==> True
print(is_valid_ipv4_address("123.52.720.55")) # Output ==> False
print(is_valid_ipv4_address("123.52.72"))     # Output ==> False
print(is_valid_ipv4_address("123"))           # Output ==> False
print(is_valid_ipv4_address("123.521.72.55")) # Output ==> False

Example 3: Using ipaddress Module

In this example, we used the ipaddress.ip_address() method from the ipaddress module to validate the IPv4 IP address.

Here is the source code of the program to validate the IPv4 IP address is valid or invalid.

Example 3: Using ipaddress Module
# Import Module
import ipaddress
 
def Isvalid_IPv4_IPAddress(ip):
    try:
        ipaddress.ip_address(ip)
        return ip+" is a valid IPv4 IP Address"
    except ValueError as errorCode:
        #uncomment below if you want to display the exception message.
        #print(errorCode)
        #comment below if above is uncommented.
        pass
        return ip+" is not a valid IPv4 IP Address"
        
        
# Print Output        
print(Isvalid_IPv4_IPAddress("123.52.72.55"))  
print(Isvalid_IPv4_IPAddress("123.52.720.55")) 
print(Isvalid_IPv4_IPAddress("123.52.72"))     
print(Isvalid_IPv4_IPAddress("123"))           
print(Isvalid_IPv4_IPAddress("123.521.72.55"))
Output

123.52.72.55 is a valid IPv4 IP Address

123.52.720.55 is not a valid IPv4 IP Address

123.52.72 is not a valid IPv4 IP Address

123 is not a valid IPv4 IP Address

123.521.72.55 is not a valid IPv4 IP Address

Example 4: Without Using Any Module

In this example, we are using any module or IP related function. In this method, we used the split() to split the string from the special character and isdigit() method to check where the element of the list is a digit or not.

Here is the source code of the program to validate the IPv4 IP address is valid or not.

Example 4: Without Using Any Module
# Define A Function To Validate an IPv4 IP Address
def Isvalid_IPv4_IPAddress(ip):
    a = ip.split('.')
    if len(a) != 4:
        return ip + " is not a Valid IPv4 IP Address"
    for x in a:
        if not x.isdigit():
            return ip + " is not a Valid IPv4 IP Address"
        i = int(x)
        if i < 0 or i > 255:
            return ip + " is not a Valid IPv4 IP Address"
    return ip + " is a Valid IPv4 IP Address"
        
# Print Output        
print(Isvalid_IPv4_IPAddress("123.52.72.55"))  
print(Isvalid_IPv4_IPAddress("123.52.720.55")) 
print(Isvalid_IPv4_IPAddress("123.52.72"))     
print(Isvalid_IPv4_IPAddress("123"))           
print(Isvalid_IPv4_IPAddress("123.521.72.55"))
Output

123.52.72.55 is a Valid IPv4 IP Address

123.52.720.55 is not a Valid IPv4 IP Address

123.52.72 is not a Valid IPv4 IP Address

123 is not a Valid IPv4 IP Address

123.521.72.55 is not a Valid IPv4 IP Address

Example 5: Using Regular Expression

In this example, we used the regular Expression.

Here is the source code of the program to validate the IPv4 IP address is Valid or not.

Example 5: Using Regular Expression
# Import Module 
import re

def Isvalid_IPv4_IPAddress(ip):
    # Regular Expression for IPv4 Version IP Address
    m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
    return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))

# Print Output        
print(Isvalid_IPv4_IPAddress("123.52.72.55"))   # Output => True
print(Isvalid_IPv4_IPAddress("123.52.720.55")) # Output => False
print(Isvalid_IPv4_IPAddress("123.52.72"))        # Output => False
print(Isvalid_IPv4_IPAddress("123"))                  # Output => False
print(Isvalid_IPv4_IPAddress("123.521.72.55")) # Output => False
print(Isvalid_IPv4_IPAddress("123.21.72.q5"))   # Output => False

Example 6: Another Example of Regular Expression to Validate IPv4 IP address

Here is the source code of the program to validate whether an IPv4 IP address is valid or not.

Example 6: Another Example of Regular Expression to Validate IPv4 IP address
# Import Module
import re

def Isvalid_IPv4_IPAddress(ip):
    reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
    if re.match(reg, ip):
        return ip+ " is a valid IPv4 IP address"
    else:
        return ip+ " is not a valid IPv4 IP address"
    
# Print the Output
print(Isvalid_IPv4_IPAddress("123.52.72.55"))
print(Isvalid_IPv4_IPAddress("123.52.720.55"))
print(Isvalid_IPv4_IPAddress("123.52.72"))
print(Isvalid_IPv4_IPAddress("123"))
print(Isvalid_IPv4_IPAddress("123.521.72.55"))
print(Isvalid_IPv4_IPAddress("123.521.72.a5"))
Output

123.52.72.55 is a valid IPv4 IP address

123.52.720.55 is not a valid IPv4 IP address

123.52.72 is not a valid IPv4 IP address

123 is not a valid IPv4 IP address

123.521.72.55 is not a valid IPv4 IP address

123.521.72.a5 is not a valid IPv4 IP address

I hope this article will help you to understand how to validate an IPv4 IP address is valid or not using python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags