This question already has an answer here:
What's the best way to validate that an IP entered by the user is valid? It comes in as a string.
This question already has an answer here:
What's the best way to validate that an IP entered by the user is valid? It comes in as a string.
IPv4:
IPv6:
The IPv6 version uses "
(?:(?<=::)|(?<!::):)
", which could be replaced with "(?(?<!::):)
" on regex engines that support conditionals with look-arounds. (i.e. PCRE, .NET)Edit:
Edit2:
I found some links discussing how to parse IPv6 addresses with regex:
Edit3:
Finally managed to write a pattern that passes all tests, and that I am also happy with.
I only needed to parse IP v4 addresses. My solution based on Chills strategy follows:
I hope it's simple and pythonic enough:
I came up with this noob simple version
From Python 3.4 on, the best way to check if an IPv6 or IPv4 address is correct, is to use the Python Standard Library module
ipaddress
- IPv4/IPv6 manipulation library s.a. https://docs.python.org/3/library/ipaddress.html for complete documentation.Example :
For other versions: Github, phihag / Philipp Hagemeister,"Python 3.3's ipaddress for older Python versions", https://github.com/phihag/ipaddress
The backport from phihag is available e.g. in Anaconda Python 2.7 & is included in Installer. s.a. https://docs.continuum.io/anaconda/pkg-docs
To install with pip:
s.a.: ipaddress 1.0.17, "IPv4/IPv6 manipulation library", "Port of the 3.3+ ipaddress module", https://pypi.python.org/pypi/ipaddress/1.0.17
Consider IPv4 address as "ip".