Foundations of Python Network Programming

(WallPaper) #1
Chapter 5 ■ Network Data aND Network errors

89

socket.gaierror: This exception is raised when getaddrinfo() cannot find a name or
service about which you ask, which is the reason for the letters g, a, and i in its name. It can
be raised not only when you make an explicit call to getaddrinfo() but also if you supply
a hostname instead of an IP address to a call like bind() or connect() and the hostname
lookup fails. If you catch this exception, you can look inside of the exception object for the
error number and message.

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> try:
... s.connect(('nonexistent.hostname.foo.bar', 80))
... except socket.gaierror as e:
... raise
...
Traceback (most recent call last):
...
socket.gaierror: [Errno -2] Name or service not known
>>> e.errno
-2
>>> e.strerror
'Name or service not known'

socket.timeout: This exception is raised only if you, or a library that you are using, decides
to set a timeout on a socket rather than be willing to wait forever for a send() or recv() to
complete. It indicates that the timeout indeed expired before the operation could complete
normally.

You will see that the Standard Library documentation for the socket module also describes an herror exception.
Fortunately, it can occur only if you use certain old-fashioned address lookup calls instead of following the practices
outlined in Chapter 4.
A big question when using higher-level socket-based protocols from Python is whether they allow raw socket
errors to hit your own code or whether they catch them and turn them into their own kind of error. Examples of both
approaches exist within the Python Standard Library itself! For example, httplib considers itself low level enough
that it can let you see the raw socket error that results from connecting to an unknown hostname.





import http.client
h = http.client.HTTPConnection('nonexistent.hostname.foo.bar')
h.request('GET', '/')
Traceback (most recent call last):
...
socket.gaierror: [Errno -2] Name or service not known





But urllib2, probably because it wants to preserve the semantics of being a clean and neutral system for
resolving URLs to documents, hides this same error and raises URLError instead.





import urllib.request
urllib.request.urlopen('http://nonexistent.hostname.foo.bar/')
Traceback (most recent call last):
...
socket.gaierror: [Errno -2] Name or service not known




Free download pdf