Python program to validate an IP Address
Last Updated :
22 Apr, 2023
Prerequisite: Python Regex
Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not.
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
Input:25.99.208.255
Output: Valid Ip address
In this program, we are using search() method of re module.
re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Let’s see the Python program to validate an IP address :
Python3
# Python program to validate an Ip address
# re module provides support
# for regular expressions
import re
# Make a regular expression
# for validating an Ip-address
regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
# Define a function for
# validate an Ip address
def check(Ip):
# pass the regular expression
# and the string in search() method
if(re.search(regex, Ip)):
print("Valid Ip address")
else:
print("Invalid Ip address")
# Driver Code
if __name__ == '__main__' :
# Enter the Ip address
Ip = "192.168.0.1"
# calling run function
check(Ip)
Ip = "110.234.52.124"
check(Ip)
Ip = "366.1.2.2"
check(Ip)
Output: Valid Ip address
Valid Ip address
Invalid Ip address
Using the ipaddress module:
The ipaddress module in Python provides classes for working with IP addresses and networks. It can be used to check if a given IP address is valid by using the ip_address function and catching any exceptions that may be thrown.
Python3
import ipaddress
def check(ip):
# Use the ip_address function from the ipaddress module to check if the input is a valid IP address
try:
ipaddress.ip_address(ip)
print("Valid IP address")
except ValueError:
# If the input is not a valid IP address, catch the exception and print an error message
print("Invalid IP address")
# Driver Code
if __name__ == '__main__':
ip = "192.168.0.1"
check(ip)
ip = "110.234.52.124"
check(ip)
ip = "366.1.2.2"
check(ip)
#This code is contributed by Edula Vinay Kumar Reddy
OutputValid IP address
Valid IP address
Invalid IP address
Time complexity: O(1)
Auxiliary Space : O(1)
METHOD 3: Using the socket module: The socket module approach only checks if the IP address is well-formed and follows the IPv4 addressing rules. It does not perform any additional checks to ensure that the IP address is reachable, allocated, or not in use.
Steps:
- Define a function validate_ip_address that takes an IP address as input.
- Inside the function, use the inet_aton method of the socket module to attempt to convert the IP address to a 32-bit packed binary format.
- If the conversion is successful, return True, indicating that the IP address is valid
- If an error is raised (meaning that the IP address is not valid), catch the error and return False, indicating that the IP address is not valid.
- Use the function to validate an IP address, and print a message indicating whether it is valid or not.
Python3
# Python program for the above approach
import socket
# Function to validate the IP Address
# using the socket module function
def validate_ip_address(ip_address):
try:
socket.inet_aton(ip_address)
return True
except socket.error:
return False
# Driver Code
ip_address = "192.168.0.1"
if validate_ip_address(ip_address):
print(f"{ip_address} is a valid IP address.")
else:
print(f"{ip_address} is not a valid IP address.")
ip_address = "110.234.52.124"
if validate_ip_address(ip_address):
print(f"{ip_address} is a valid IP address.")
else:
print(f"{ip_address} is not a valid IP address.")
ip_address = "666.1.2.2"
if validate_ip_address(ip_address):
print(f"{ip_address} is a valid IP address.")
else:
print(f"{ip_address} is not a valid IP address.")
ip_address = "25.99.208.255 "
if validate_ip_address(ip_address):
print(f"{ip_address} is a valid IP address.")
else:
print(f"{ip_address} is not a valid IP address.")
Output192.168.0.1 is a valid IP address.
110.234.52.124 is a valid IP address.
666.1.2.2 is not a valid IP address.
25.99.208.255 is a valid IP address.
Time Complexity: O(1) because the inet_aton method has a constant time complexity regardless of the length of the input IP address.
Space Complexity: O(1) because the amount of memory used by the function does not depend on the length of the input IP address.
Similar Reads
Python program to find the type of IP Address using Regex
Prerequisite: Python Regex Given an IP address as input, write a Python program to find the type of IP address i.e. either IPv4 or IPv6. If the given is neither of them then print neither. What is an IP (Internet Protocol) Address?Every computer connected to the Internet is identified by a unique fo
2 min read
Python program to check the validity of a Password
In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions.Primary conditions for password validation:Minimum 8 characters.The alphabet must be between [a
3 min read
Check if email address valid or not in Python
Given a string, write a Python program to check if the string is a valid email address or not. An email is a string (a subset of ASCII characters) separated into two parts by the @ symbol, a "personal_info" and a domain, that is [email protected]: Email Address Validator using re.match()P
3 min read
Validate an IP address using Python without using RegEx
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 Protoco
2 min read
Program to convert IP address to hexadecimal
Given an IP Address and task is to change the IP address equivalent to the hexadecimal value. Examples: Input : 127.0.0.1Output : 0x7f000001Input : 172.31.0.2Output : 0xac1f0002Explanation: Using the Library function to convert the IP address into the hexadecimal value we use the " arpa/inet.h " hea
4 min read
Python List Checking and Verification Programs
Lists in Python are versatile, but often, we need to verify their contents, structure, or relationships with other lists. Whether we're checking for duplicates, order, existence of elements or special conditions, Python provides efficient ways to perform these checks.This article covers various list
4 min read
Finding IP Address using Python
An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g., router, mobile, etc.) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in huma
2 min read
Input Validation in Python String
In Python, string input validation helps ensure that the data provided by the user or an external source is clean, secure and matches the required format. In this article, we'll explore how to perform input validation in Python and best practices for ensuring that strings are correctly validated.Pyt
2 min read
Input Validation in Python
Input validation ensures that data entered by the user is correct, safe, and in the expected format. In Python, input validation is essential for creating robust, error free programs that can handle incorrect or unexpected inputs. Python provides several ways to validate user inputs, let's explore s
2 min read
Password validation in Python
Let's take a password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of few conditions. Conditions for a valid password are: Should have at least one number.Should have at least one uppercase and one lowercase c
4 min read