Skip to content

Instantly share code, notes, and snippets.

@benhagen
Last active March 19, 2020 19:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benhagen/5296795 to your computer and use it in GitHub Desktop.
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
@chanj
Copy link

chanj commented May 17, 2013

Hagen - https://pypi.python.org/pypi/netaddr. There are a couple more useful similar libs but this is the one I've used.

bad = "hagen"
good = "10.0.0.1"
netaddr.ip.IPAddress(bad)
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.7/site-packages/netaddr-0.7.10-py2.7.egg/netaddr/ip/init.py", line 315, in init
'address from %r' % addr)
AddrFormatError: failed to detect a valid IP address from 'hagen'
netaddr.ip.IPAddress(good)
IPAddress('10.0.0.1')

@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