Skip to content

Network Programming with Sockets

Beginning of the lesson

Network Programming with Sockets

Talk to the network directly, one byte at a time, with the socket module

Big Idea: A socket is one endpoint of a two-way network connection. A TCP socket gives you an ordered, reliable byte stream between two endpoints, each identified by an IP address and a port number. The socket module is Python's thin wrapper over the operating system's BSD sockets API. Everything higher up — HTTP clients, asyncio, web frameworks, database drivers — is ultimately built on these calls. Knowing them demystifies the whole stack.
By the end you will be able to:
  • create a TCP socket and understand AF_INET / SOCK_STREAM,
  • walk a server through bind -> listen -> accept and a client through connect,
  • send and receive bytes (never str) and handle partial reads,
  • frame messages so a byte stream becomes discrete messages,
  • build a minimal echo/chat server and reason about its trade-offs.

1. What a socket actually is

A socket is an operating-system object — a file-like handle — that represents one end of a network conversation. You create one by naming an address family and a socket type:

import socket

# AF_INET  -> IPv4 addressing (host, port)
# SOCK_STREAM -> TCP: an ordered, reliable byte stream
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The pair (host, port) is the address. The host is an IP address such as "127.0.0.1" (this machine) or "0.0.0.0" (every interface); the port is a 16-bit number (0–65535) that lets one machine host many independent services at once. A connection is uniquely identified by the four-tuple (local ip, local port, remote ip, remote port), which is why one server port can serve thousands of clients simultaneously.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers