I would like to validate IP addresses from a list that may contain incorrectly formated addresses or other garbage. If the field does not contain a properly formated field, simply continue ignoring that field.
Per How to validate IP address in Python? it seems that there are two methods two accomplish this, REGEX or socket.inet_aton()
.
Below is an attempt to use socket.inet_aton()
to parse a CSV and check the field if it is an IPv4 address. Currently it prints the garbage or not properly formatted IP addresses. Any tips on printing the inverse, or IP that are proper IP addresses?
Update
Numeric fields are not printing in discrete octet notation, i.e. 12345 prints. How could non-octet notation be filtered out?
for data in import_text('data.csv', ','):
try:
socket.inet_aton(data)
except socket.error:
continue
print (data)