Friday, July 5, 2013

Python script for checking if an IP address is valid

To know if an IP address is valid, here is a simple python script. Let us name the script as chkip.py

Pass the IP address to be validated as an argument for this program, like follows
python chkip.py  <IP Address>


#!/usr/bin/python
import re
import sys

def check_ip_validity(ipaddr):
    ValidIpAddressRegex = '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
    ip_match = re.search(ValidIpAddressRegex,ipaddr)
    if ip_match:
       ip = 1
    else:
       ip = 0
    return ip

def main():
    ip = 0
    if check_ip_validity(sys.argv[1]):
       print "Valid IP"
    else:
       print "Not a valid IP"

if __name__ == '__main__':
    main()

1 comment:

  1. Traceback (most recent call last):
    File "ip.py", line 21, in
    main()
    File "ip.py", line 15, in main
    if check_ip_validity(sys.argv[1]):
    IndexError: list index out of range

    ReplyDelete