Skip to content

Instantly share code, notes, and snippets.

@benhagen
Last active March 19, 2020 19:23
Show Gist options
  • Select an option

  • Save benhagen/5296795 to your computer and use it in GitHub Desktop.

Select an option

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.
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
@jbnance
Copy link

jbnance commented Nov 23, 2016

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.

@Pr1meSuspec7
Copy link

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