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.
Don't parse it. Just ask.
The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.
However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.
If you're using Python 3.3 or later, it now includes the ipaddress module:
For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:
This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode:
ipaddress.ip_address(u'127.0.0.1')
.I think this would do it...
I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.
I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.
Here is my regex that passes all of the examples in that Perl script:
I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.
You can run the script with test result and example arguments in the form of "[result]=[example]", so like:
or you can simply run all of the tests by specifying no arguments, so like:
Anyway, I hope this helps somebody else!