1. Home
  2. Computing & Technology
  3. Python

Building a Simple Web Server in Python

From , former About.com Guide

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: [blockquote] socket_object.setsockopt(level, option_name, value) [/blockquote] 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.

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Networking
  5. Python Web Server: Setting Socket Options

©2009 About.com, a part of The New York Times Company.

All rights reserved.