Last modified: Jun 11, 2023 By Alexander Williams
Python: 3 methods to check if a string is a valid IP address
In this article, we will explore different methods and techniques to check the validity of a string representing an IP address in Python.
Check if String is a valid IP using Iptools
The iptools
library is a tool that offers IP address manipulation and validation features. We can use the
library to check whether the string is a valid IP address. However, before we proceed, let's install the library.
Installing via pip:
pip install iptools
Once you have installed the iptools
library, you can use the following example to verify if a string is a valid IP address:
from iptools import IpRange
ip_address = "192.168.0.1"
if IpRange(ip_address):
print("Valid IP address")
else:
print("Invalid IP address")
Output:
Valid IP address
In this example, the IpRange()
function from the "iptools" library is used to validate the provided IP address. If the IP address is considered valid, the code will output "Valid IP address"; otherwise, it will output "Invalid IP address".
Check if String is a valid IP using IPy
IPy is a library for handling IPv4 and IPv6 addresses and networks. We can also use this library to check if a string is a valid IP address
Installation via pip:
pip install IPy
Let's see how to use it.
import IPy
ip_address = "192.168.0.1"
ip = IPy.IP(ip_address)
if ip.iptype() == 'PUBLIC' or ip.iptype() == 'PRIVATE':
print("Valid IP address")
else:
print("Invalid IP address")
Output:
Valid IP address
Let me explain the code:
- Import the
IPy
module. - Use the
IPy.IP()
function to create an IP object with the given string. - Use the
iptype()
method to check the type of the IP object.
Check if String is a valid IP using Socket
Another method to check if the string is a valid IP address is the Socket module. This library offers functionalities to establish connections, send and receive data, and perform network-related tasks like IP address validation.
Let's see an example::
ip_address = "192.168.0.1"
try:
socket.inet_aton(ip_address)
print("Valid IP address")
except socket.error:
print("Invalid IP address")
Output:
Valid IP address
However, in this example: we've used the inet_aton()
function to attempt to convert the IP address string to a packed 32-bit binary format.
Conclusion
In this article, we explored various methods to check if a string is a valid IP address in Python. We discussed three different approaches: using, the socket
module, IPy
and the ipaddress
module.
Each method offers advantages and can be used based on specific requirements and the Python version.