Change language

Python program to check IP address

|

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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method