I'm trying to validate whether some incoming data is a valid IP or subnet mask. I would just like some input to see if there is a better way of doing it. In most cases I have valid IPs or subnet marks coming in. Rarely I'll see a FQDN which I would like to a look up and get the ip.
Example of my first attempt. I feel like maybe this could be further reduced.
import ipaddress
import socket
data = ['832', 'dsdsds', '192.0.2.1', '192.0.2.0/24', 'google.com']
validated_data = []
for value in data:
try:
if ipaddress.ip_address(value):
validated_data.append(value)
except ValueError as e:
try:
if ipaddress.ip_network(value):
ipv4 = ipaddress.ip_network(value)
for x in ipv4.hosts():
validated_data.append(x.exploded)
except ValueError as e:
try:
if socket.gethostbyname(value):
ip = socket.gethostbyname(value)
validated_data.append(ip)
except socket.error as e:
print(f"Invalid Data - {value} - {e}")
print(validated_data)