IP Address Validation in Python

I recently had to write a function to validate an IP address so thought I would share the process. You will need the really handy python module called, wait for it, ipaddress

So lets get that imported first of all

import ipaddress

Once imported we should create a function which will take the IP address as a parameter and then validate it.

def validate_ip(given_ip):
  try:
    ip = ipaddress.ip_address(given_ip)
    #slight issue with broadcast addresses, if IP ends in 255 or 0 then it should not be valid but will show as valid above so lets filter that out.
    ip_split = given_ip.split('.')
    if ip_split[3] != "0" and ip_split[3] != "255":
      return True
    else:
      return False
  except ValueError:
    return False
  except:
    print('Error : %s  ip' % given_ip)

if validate_ip("192.168.1.1"):
  print("Valid IP")

Now one issue I found with this module is that it would say that an address ending in 0 or 255 was valid. Now technically it is valid but they are not useable addresses, so 255 for example is what is called the broadcast address. So I have added an IF clause to filter these two values out and mark them as invalid if they are presented.

This code is part of my new ScanLan program freely available through Github

You can fork the code and play with it for yourself on Repli.it