Sometimes, we want to validate IP address in Python.
In this article, we’ll look at how to validate IP address in Python.
How to validate IP address in Python?
To validate IP address in Python, we can use the ipaddress
library.
To install it, we run
pip install ipaddress
Then we use it by writing
import ipaddress
# ...
try:
ip = ipaddress.ip_address(ip_address)
print(ip, ip.version)
except ValueError:
print('invalid ip')
to call ipaddress.ip_address
to try to parse the ip_address
string.
If it’s successful, then we get the IP address from the ip
object.
And we get the IP address version from ip.version
.
Otherwise, a ValueError
will be thrown.
Conclusion
To validate IP address in Python, we can use the ipaddress
library.