Program to validate IP address using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to validate IP address using regex

Introduction

An IP address consists of numbers and characters. There are two versions of IP address: IPv4 and IPv6. The task is to validate the given IP address using regex expression.

Program to validate IP address using regex

Program

import re
def check_IP(ip_IP):
# Regular expression for IPv4and IPv6
    re_IPv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|"\
            "2[0-4][0-9]|25[0-5])\\.){3}"\
            "([0-9]|[1-9][0-9]|1[0-9][0-9]|"\
            "2[0-4][0-9]|25[0-5])"
    re_IPv6 = "((([0-9a-fA-F]){1,4})\\:){7}"\
             "([0-9a-fA-F]){1,4}"
     
    exp_IPv4 = re.compile(re_IPv4)
    exp_IPv6 = re.compile(re_IPv6)
    if (re.search(exp_IPv4, ip_IP)):
        print("The given input is a valid IPv4!")
    elif (re.search(exp_IPv6, ip_IP)):
        print("The given input is a valid IPv6!")
    return "The given input is a invalid IP!"
ip_IP= input("Enter the IP address to validate:")
check_IP(ip_IP)

Output

Program to validate IP address using regex Output

Explanation

In the above python code, we have passed the regular expression for IPv4 and IPv6 in search() method along with the input string. If the regex pattern (of  IPv4 and IPv6) matches with the input string, the output “valid” is returned otherwise the output “invalid” is returned.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author