[python]Validate an ip address

On python3 there is a build in ipaddress module which can be referenced to check if the user’s input is an ip address, no more using the complicated regex to match, this module helps to check and throws an exception if the ip address is invalid.

See below sample code

import ipaddress

def validate_ipaddress(ip):
    try:
        ipaddress.ip_address(ip)
        return True
    except ValueError as errorCode:
        #uncomment below if you want to display the exception message.
        #print(errorCode)
        #comment below if above is uncommented.
        pass
        return False


def main():

    ipaddr=input("Please enter an ip address(q for quit):\n")
    while(ipaddr.lower()!='q'):

        if(validate_ipaddress(ipaddr)==False):
            print("This is an invalid address.")
        else:
            print("IP address {} is valid".format(ipaddr))
        ipaddr = input("Please enter an ip address(q for quit):\n")


if __name__ == "__main__":
    main()

So here are several tests:

Please enter an ip address(q for quit):
10.1.1.1
IP address 10.1.1.1 is valid

Suppose an out of range number is written:

Please enter an ip address:
300.300.300300
'300.300.300300' does not appear to be an IPv4 or IPv6 address
This is an invalid address.

Suppose a string is entered by a user:

Please enter an ip address:
object
'object' does not appear to be an IPv4 or IPv6 address
This is an invalid address.

Below test is after i suppress the exception:

Please enter an ip address(q for quit):
object
This is an invalid address.

This sample code can be used to validate if user’s have input the correct address or if you are doing firewall automation user may put in object or object group or address, so your script can include to check which category has user entered.

Advertisements
This entry was posted in General stuffs, Python, Scripting and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s