1. Technology

Building a Simple Web Server in Python

By

6 of 10

Setting Socket Options

After creating the socket, we then need to set the socket options. For any socket object, you can set the socket options by using the setsockopt() method. The syntax is as follows:

socket_object.setsockopt(level, option_name, value) For our purposes, we use the following line:

c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

The term 'level' refers to the categories of options. For socket-level options, use SOL_SOCKET. For protocol numbers, one would use IPPROTO_IP. SOL_SOCKET is a constant attribute of the socket. Exactly which options are available as part of each level are determined by your operating system and whether you are using IPv4 or IPv6.

The documentation for Linux and related Unix systems can be found in the system documentation. The documentation for Microsoft users can be found on the MSDN website. As of this writing, I have not found Mac documentation on socket programming. As Mac is roughly based upon BSD Unix, it is likely to implement a full complement of options.

In order to ensure reusability of this socket, we use the SO_REUSEADDR option. One could restrict the server to only run on open ports, but that seems unnecessary. Do note, however, that if two or more services are deployed on the same port, the effects are unpredictable. One cannot be certain which service will receive which packet of information.

Finally, the '1' for a value is the value by which the request on the socket is known in the program. In this way, a program can listen on a socket in very nuanced ways.

  1. About.com
  2. Technology
  3. Python
  4. Networking
  5. Python Web Server: Setting Socket Options

©2014 About.com. All rights reserved.