top of page

Socket Programming in Python

Updated: Nov 3, 2020

Sockets and the socket API are used to send messages across a network.

The network can be a logical, local network to the computer, or one that’s physically connected to an external network like the internet.

In computer networking, localhost is a hostname that refers to the current computer used to access it. It is used to access the network services that are running on the host via the loopback network interface. Using the loopback interface bypasses any local network interface hardware.

The local loopback mechanism may be used to run a network service on a host without requiring a physical network interface, or without making the service accessible from the networks the computer may be connected to. For example, a locally installed website may be accessed from a Web browser by the URL http://localhost to display its home page.

The name localhost normally resolves to the IPv4 loopback address, and to the IPv6 loopback address ::1

Goal: write your own client-server applications.

Three different iterations of building a socket server and client with Python:

  1. We’ll start the tutorial by looking at a simple socket server and client.

  2. Once you’ve seen the API and how things work in this initial example, we’ll look at an improved version that handles multiple connections simultaneously.

  3. Finally, we’ll progress to building an example server and client that functions like a full-fledged socket application, complete with its own custom header and content.

Understand how to use the main functions and methods in Python’s socket module.


Sockets have a long history. Their use originated with ARPANET in 1971 and later became an API in the Berkeley Software Distribution (BSD) operating system released in 1983 called Berkeley sockets.

When the Internet took off in the 1990s with the World Wide Web, so did network programming. Web servers and browsers weren’t the only applications taking advantage of newly connected networks and using sockets. Client-server applications of all types and sizes came into widespread use.

Today, although the underlying protocols used by the socket API have evolved over the years, and we’ve seen new ones, the low-level API has remained the same.

The most common type of socket applications are client-server applications, where one side acts as the server and waits for connections from clients. This is the type of application that I’ll be covering in this tutorial. More specifically, we’ll look at the socket API for Internet sockets, sometimes called Berkeley or BSD sockets. There are also Unix domain sockets, which can only be used to communicate between processes on the same host.

Recent Posts

See All

Generative AI report

Top GenAI companies: OpenAI Google Anthropic Meta Mistral Stability AI MidJourney Top GenAI Models GPT 4 Gemini 1.5 Llama2 Mistral Claude Stable Diffusion


bottom of page