import os, ipaddress
os.system('cls')
while True:
ip = input('IP Validity Check: ')
try:
print(ipaddress.ip_address(ip))
print('IP Valid')
except:
print('-' * 79)
print('IP Not Valid !!!!')
finally:
if ip == 'q':
print('Script Finished')
break
- The first line of code imports the operating system and ipaddress modules.
- The
os.system('cls')
line clears the console screen. - The
while True:
statement initiates an infinite loop. - The
ip = input('IP Validity Check: ')
line prompts the user to enter an IP address to be checked for validity and stores it in theip
variable. - The
try:
statement initiates a try-except block, which is used to handle errors in the code. - The
ipaddress.ip_address(ip)
line checks whether the IP address entered by the user is valid or not by passing it to theip_address()
method of the ipaddress module. If it is valid, the method returns the IP address object, and the code inside the try block is executed. - The
print('IP Valid')
line prints "IP Valid" to the console if the IP address is valid. - The
except:
statement catches any exception that occurs in the try block. - The
print('-' * 79)
line prints a line of 79 dashes to the console to visually separate the error message from the rest of the output. - The
print('IP Not Valid !!!!')
line prints "IP Not Valid !!!!" to the console if the IP address entered by the user is not valid. - The
finally:
statement is executed whether or not an exception is caught in the try block. - The
if ip == 'q':
statement checks if the user has entered "q" to quit the program. If so, thebreak
statement is executed, which exits the while loop and terminates the program.
Simple version (for one IP) - no error checking
import os, ipaddress
os.system('cls')
ip = input('IP Validity Check: ')
if ipaddress.ip_address(ip):
print('OK')
The given code is used to check the validity of an IP address. Here's how it works:
-
The code begins by importing the 'os' and 'ipaddress' modules.
-
It then clears the console screen using the 'os.system' function with the 'cls' argument.
-
The user is prompted to enter an IP address to check its validity using the 'input' function.
-
The 'ipaddress.ip_address' function is used to check if the entered IP address is valid.
-
If the IP address is valid, the program prints 'OK', indicating that the IP address is valid.
-
If the IP address is not valid, the program raises an exception, indicating that the IP address is not valid.
In summary, the program checks the validity of the entered IP address and prints 'OK' if the IP address is valid. If the IP address is not valid, an exception is raised.
No comments:
Post a Comment