im using the ipaddress module in python. Here is my current scenario. we have self service portal of sorts that will promt the user to enter an IP address. We will allow this to be an individual IP like 165.136.219.5 or something like this 165.136.219.0/24. Once the have entered the data, i want my code to check and ensure its either a valid IPV4 address or a valid IPV4 CIDR.
when i do something like this code below, i get a failure that "/" isnt a valid character. Am i using the ipaddress package wrong ?
newIpAddress = input("Please enter the IP address for SFTP access: ")
if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:
Im basically grabbing input from a end user, and then I want to use an if statement basically stating so long as its either a valid IPV4 IP or a valid IPV4 CIDR then go do some tasks, then ill do some else statements that print out some verbiage about not meeting the address or network requirements.
my current code spits out the the following error:
Unexpected '/' in '165.136.219.0/24' File "C:\Users\myname\Documents\my_Scripts\PaloAlto\sftpNew.py", line 21, in if ipaddress.IPv4Address(newIpAddress) == True or ipaddress.IPv4Network(newIpAddress) == True:
The ipaddress
class does not appear to provide any convenience methods for determinig whether a string represents a valid IPv4 address versus a valid IPv4 network versus neither a valid address or network.
However, you can build your own rudimentary functionality to check to see if one or the other throws an exception and return true
or false
and use it in your conditional:
import ipaddress
def valid_ip_or_cidr(ip):
try:
ipaddress.IPv4Address(ip)
print('valid as address')
return True
except:
try:
ipaddress.IPv4Network(ip)
print('valid as network')
return True
except:
print('invalid as both an address and network')
return False
valid_ip_or_cidr('192.168.1.1')
# valid as address
# True
valid_ip_or_cidr('192.168.1.0/24')
# valid as network
# True
valid_ip_or_cidr('foo')
# invalid as both an address and network
# False
In your context, this would be implemented in your conditional as:
newIpAddress = input("Please enter the IP address for SFTP access: ")
if valid_ip_or_cidr(newIpAddress):
# code to execute if validation succeeds