Skip to content

Networking in Python

diagram what the requests library is doing that a raw socket is not mermaid
The two ends of this picture are the same connection. A socket gives you bytes; everything above it -- finding the host, negotiating TLS, framing an HTTP message, decoding the body -- is work someone has to do. Writing it yourself is the reason to reach for a library, not a weakness of sockets.

Networking is how computers exchange data.

Key concepts:

  • IP address: identifies a machine
  • Port: identifies a program/service on that machine
  • Protocol: rules for communication

Common protocols:

  • TCP: reliable (web, SSH)
  • UDP: fast, not guaranteed (streaming, DNS)
  • HTTP/HTTPS: web protocol (built on TCP)
  • Make HTTP requests (APIs) using requests and urllib
  • Work with JSON data
  • Build a basic HTTP server
  • Use sockets for low-level TCP communication
  • Timeouts, retries, and error handling

Always be careful when handling:

  • user input from the internet
  • authentication tokens
  • opening ports on public machines
sketch Everything requests does above a raw socket p5.js
Both ends of this picture are the same connection. A socket gives you an ordered stream of bytes and nothing else -- finding the host, negotiating TLS, framing an HTTP message and decoding the body are all work somebody has to do. Writing that yourself is the reason to reach for a library, not a shortcoming of sockets.
pch.quizTag pch.quizDefaultTitle
  1. What does a TCP socket actually guarantee?

    pch.quizShowAnswer

    B — Bytes arrive in order and intact, with no message boundaries — Measured elsewhere on this site: `sendall(b'HELLO')` then `sendall(b'WORLD')` read by `recv(4)` came back as `[b'HELL', b'O', b'WORL']`. Framing is the application's job.

  2. Which of these does a raw socket NOT do for you?

    pch.quizShowAnswer

    C — Parse HTTP headers — Ordering, retransmission and checksums are TCP's job. Everything protocol-shaped above that — HTTP framing, TLS, content decoding — is written on top.

  3. What is the first thing `requests.get('https://host/path')` must do?

    pch.quizShowAnswer

    B — Resolve the hostname to an IP address — You cannot connect to a name. DNS resolution happens first, then the TCP connection, then the TLS handshake, and only then does any HTTP get written.

  4. Why use a `Session` for repeated calls to the same host?

    pch.quizShowAnswer

    B — It reuses the connection and shares headers and cookies — Reusing the connection skips the TCP and TLS handshakes on every subsequent request, which is usually the dominant cost for small responses.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading