Python program to check IP address

Python Methods and Functions | Regular Expressions

Given an IP address as input, write a Python program to check if the given IP address is valid or not.

What is an IP address?
Every computer connected to the Internet is identified by a unique four-part string known as its IP address. An IP address (version 4) consists of four numbers (each from 0 to 255) separated by periods. The IP address format is a 32-bit numeric address written as four decimal numbers (called octets ) separated by periods; each number can be written as 0 to 255 (e.g. 0.0.0.0 to 255.255.255.255).

Examples :

  Input :  192.168.0.1  Output:  Valid Ip address  Input:  110.234.52.124  Output:  Valid Ip address  Input:  666.1.2.2  Output:  Invalid Ip addess 

In this program we use the method search () module re .

re.search (): this method either returns None (if the pattern does not match) or re.MatchObject which contains information about the matching part of the string. This method stops after the first match, so it's better for checking regular expressions than for extracting data.

Let's see a Python program to check an IP address:

# Python program to check IP address

 
# re module provides support
# for regular expressions

import re

 
# Make a regular expression
# to check the IP address

regex = & # 39; & # 39; & # 39; ^ (25 [0-5] | 2 [0-4] [0-9] |? [0-1] [0-9] [0-9]) / (.

25 [0-5] | 2 [0-4] [0-9] | ?. [0 -1] [0-9] [0-9]) / (

25 [ 0-5] | 2 [0-4] [0-9] | ?. [0-1] [0-9] [0-9]) / (

25 [0-5] | 2 [0-4] [0-9] |? [0-1] [0-9] [ 0-9]) & # 39; & # 39; "

  
# Define a function for
# confirm IP address

def check (Ip): 

 

# pass regex

  # and a string in the search () method

  if (re.search (regex, Ip)): 

  print ( " Valid Ip address "

 

else

print ( "Invalid Ip address"

 

 
Driver code

if __ name__ = = '__main__'

  

# Enter the IP address

Ip = "192.168.0.1"

 

# call the run function

check (Ip)

 

Ip = "110.234.52.124"

check (Ip)

 

Ip = "366.1.2.2"

check (Ip)

Output:

 Valid Ip address Valid Ip address Invalid Ip address 




Get Solution for free from DataCamp guru