Last active
March 19, 2020 19:23
-
-
Save benhagen/5296795 to your computer and use it in GitHub Desktop.
Python function to determine if a string is like an IPv4 address. Its lame but works; to be improved at a later date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_ipv4(ip): | |
match = re.match("^(\d{0,3})\.(\d{0,3})\.(\d{0,3})\.(\d{0,3})$", ip) | |
if not match: | |
return False | |
quad = [] | |
for number in match.groups(): | |
quad.append(int(number)) | |
if quad[0] < 1: | |
return False | |
for number in quad: | |
if number > 255 or number < 0: | |
return False | |
return True |
Note that this will throw an exception if you pass a string such as '192.168..' because the regex allows 0-3 but the 0-255 test doesn't take into account empty quads. Simple workaround is to just change the regex to {1,3}.
Also note that this returns true for zero-padded octets such as 192.168.01.1, which may not be what you expect. You could insert something crude such as:
if len(number) > 1 and number[0] == '0':
return False
...in the first for loop.
Hi Ben,
this is my version of the function: https://gist.github.com/Pr1meSuspec7/d6154c4f9b01d2ea80cd5fd51ddfb8eb
I hope it can help you
Bye
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hagen - https://pypi.python.org/pypi/netaddr. There are a couple more useful similar libs but this is the one I've used.