I am trying to create a program to check whether the given input is a valid hostname, valid IP, or neither. The program is able to recognize a valid hostname or IP. However, If I try to put something random, like "xyz", it doesn't print the error message I want.
import socket
if __name__ == '__main__':
hostname = 'hyuiolpp'
if socket.gethostbyname(hostname) == hostname:
print('{} is a valid IP address'.format(hostname))
elif socket.gethostbyname(hostname) != hostname:
print('{} is a valid hostname'.format(hostname))
else:
print("Something is wrong")
The error I get:
Traceback (most recent call last):
File ".....", line 5, in <module>
if socket.gethostbyname(hostname) == hostname:
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
The HostName test performs DNS lookup and provides information about how a domain or hostname (www.yourdomain.com) is resolved to an IP address (69.147. 114.210). Common use of the HostName test is to verify that the DNS records are correct and specific domain points to the correct IP address.
The FILTER_VALIDATE_IP filter validates an IP address.
You can add a simple try
block and catch the error(s) generated.
import socket
def main():
hostname = 'hyuiolpp'
try:
if socket.gethostbyname(hostname) == hostname:
print('{} is a valid IP address'.format(hostname))
elif socket.gethostbyname(hostname) != hostname:
print('{} is a valid hostname'.format(hostname))
except socket.gaierror:
print("Something is wrong")
if __name__ == '__main__':
main()
Few Things:
1.) I added a main()
function and just called it in your __main__
check as it seems to be a better practice. I don't think there's anything wrong with yours, but from my experiences most people code this way, probably because it's easier to comment out one #main()
than dozens of lines during debug or even to test out different functions locally.
2.) You'll probably want to handle each error raised differently. During your unit testing you'll find out what other errors (beside socket.gaierror) are raised and what errors you might anticipate, and figure out how your program is supposed to handle those scenarios. You can add extra except
s for each error (or group them together if the group is handled one way). Using just except:
to catch all is generally considered a bad practice unless you're okay with that.
Use a try-except block. The problem is that xyz
causes a run-time fault in gethostbyname
-- instead of a False
value, the program turns over to the error handler. Something like
try:
sock = socket.gethostbyname(hostname)
if sock == ...
except:
print("Something is wrong")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With