1. Home
  2. Computing & Technology
  3. Python

Building a Simple Web Server in Python

By Al Lukaszewski, About.com

5 of 10

Creating a Socket

Whether to request information or to serve it, in order to access the Internet, we need to create a socket. The syntax for this call is as follows:

<variable> = socket.socket(<family>, <type>)

The recognised socket families are:

  • AF_INET: IPv4 protocols (both TCP and UDP)
  • AF_INET6: IPv6 protocols (both TCP and UDP)
  • AF_UNIX: UNIX domain protocols
The first two are obviously internet protocols. Anything that travels over the internet can be accessed in these families. Many networks still do not run on IPv6. So, unless you know otherwise, it is safest to default to IPv4 and use AF_INET.

The socket type refers to the type of communication used through the socket. The five socket types are as follows:

  • SOCK_STREAM: a connection-oriented, TCP byte stream
  • SOCK_DGRAM: UDP transferral of datagrams (self-contained IP packets that do not rely on client-server confirmation)
  • SOCK_RAW: a raw socket
  • SOCK_RDM: for reliable datagrams
  • SOCK_SEQPACKET: sequential transfer of records over a connection
By far, the most common types are SOCK_STEAM and SOCK_DGRAM because they function on the two protocols of the IP suite (TCP and UDP). The latter three are much rarer and so may not always be supported.

So let's create a socket and assign it to a variable.

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

5 of 10

Explore Python

More from About.com

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

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

All rights reserved.