1. Home
  2. Computing & Technology
  3. Python

Building a Web Client in Python

By Al Lukaszewski, About.com

5 of 9

Creating a Socket With Python

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>) </blockquote>

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. The latter three are much rarer and so may not always be supported.

Let's therefore create a socket and assign it to variable; here I use c (for connection). [blockquote shade=yes] c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

5 of 9

Explore Python

More from About.com

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

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

All rights reserved.