In: Computer Science
Using PyCharm Edu on Windows, need to ask for an IP address (input), use "ipaddress.ip_address" to validate it, only if error (value or type) set the default IP to 192.168.1.1, if no error then use the original input. This is the code so far and I need help please.
def req_Address(): while True: try: address = str(ipaddress.ip_address(input("Please enter the ip address you wish scan [192.168.1.1]: "))) except (ValueError, TypeError): print("Not a valid IP address") else: print("Setting the default address to 192.168.1.1") address = '192.168.1.1' print("We will use: " + address) print()
Code:
import ipaddress # importing ipaddress to check the ip address
def req_Address(): # fucntion to get the IP address
try:
address = input("Please enter the ip address you wish to scan[192.168.1.1]: ") # user input for ip address
ipaddress.ip_address(address) # checking the ip address if any error occured
print("We will use: " + address) # printig the message
except ValueError or TypeError: # raising exception for Value and type errors
print("Not a valid IP address") # message for Invalid IP input
print("Setting the default address to 192.168.1.1") # message
address = '192.168.1.1' # setting the default IP
print("We will use: " + address) # printig the message
print() # for new line
return address # return IP address
req_Address() # calling fucntion
Sample output:
Code: Screenshot:
Note: As the name of the function suggest that some variable is requesting the ip address so I have returned the IP address in the req_address() fucntion.
line number 17 is just for demonstration purpose.
Note: Please let me know if you have any doubt or you need any modification in the code.