How it works...

In Python, passing command-line arguments to a script and parsing them in the script can be done using the argparse module. This is available in Python 2.7. For earlier versions of Python, this module is available separately in Python Package Index (PyPI). You can install this via easy_install or pip.

In this recipe, three arguments are set up—a hostname, port number, and filename. The usage of this script is as follows:

$ python 1_7_socket_errors.py --host=<HOST> 
--port=<PORT> --file=<FILE>
In the preceding recipe, msg.encode('utf-8')
encodes the message into UTF-8, and
buf.decode('utf-8') decodes the received UTF-8
format.

If you try the preceding recipe with a non-existent host, this script will print an address error as follows:

$ python 1_7_socket_errors.py 
--host=www.pytgo.org --port=8080
--file=1_7_socket_errors.py
Address-related error connecting to
server: [Errno -2] Name or service not known

If there is no service on a specific port and if you try to connect to that port, then this will throw a connection timeout error as follows:

$ python 1_7_socket_errors.py 
--host=www.python.org --port=8080
--file=1_7_socket_errors.py

This will return the following error since the host, www.python.org, is not listening on port 8080:

Connection error: [Errno 110] Connection timed out
  

However, if you send an arbitrary request as a correct request to a correct port, the error may not be caught at the application level. For example, running the following script returns no error, but the HTML output tells us what's wrong with this script:

$ python 1_7_socket_errors.py 
--host=www.python.org --port=80
--file=1_7_socket_errors.py
HTTP/1.1 500 Domain Not Found Server: Varnish Retry-After: 0 content-type: text/html Cache-Control: private, no-cache connection: keep-alive Content-Length: 179 Accept-Ranges: bytes Date: Thu, 01 Jun 2017 22:02:24 GMT Via: 1.1 varnish Connection: close <html> <head> <title>Fastly error: unknown domain </title> </head> <body> Fastly error: unknown domain: . Please check that this domain has been added to a service.</body></html>

In the preceding example, four try-except blocks have been used. All blocks use socket.error except for the second block, which uses socket.gaierror. This is used for address-related errors. There are two other types of exceptions—socket.herror is used for legacy C API, and if you use the settimeout() method in a socket, socket.timeout will be raised when a timeout occurs on that socket.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.7.102