Port numbers & dictionaries

Ports and services

Lesson 9 of 20 · 8 min · Module 3: Ports and endpoints

An IP address finds the computer; a port number finds the program on it. Web servers usually listen on 80 and 443, SSH on 22.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Explain what a port identifies
  • Look up values with dict.get
  • Validate a numeric range

The idea

Port numbers range from 0 to 65535. Ports 0 to 1023 are well-known (reserved for standard services), 1024 to 49151 are registered, and 49152 to 65535 are dynamic: short-lived ports chosen by clients.

SERVICES = {22: "ssh", 443: "https"}
print(SERVICES.get(22, "unknown"))

01Address plus port

192.168.1.10:22 means "the SSH program on 192.168.1.10". One server can run a web server, a database, and SSH at once, each on its own port.

02Defaults avoid KeyError

SERVICES[8081] raises KeyError, while SERVICES.get(8081, "unknown") returns a safe default. Choose get when a missing key is normal.

SERVICES = {22: "ssh"}
print(SERVICES.get(8081, "unknown"))
Output
unknown

03Ports are 16-bit numbers

16 bits give 65,536 values, 0 to 65535. Anything else cannot be a port, so raising ValueError stops bad data early.

Your turn

Write service_for(port) that returns the service name for 22 (ssh), 25 (smtp), 53 (dns), 80 (http), 443 (https), 3306 (mysql), and 5432 (postgresql), and "unknown" otherwise. Write port_range(port) that returns "well-known", "registered", or "dynamic", and raises ValueError for numbers outside 0 to 65535.

What the checks look for

  • Names common services
  • Returns unknown for other ports
  • Classifies port ranges at their boundaries
  • Rejects ports outside 0–65535
Try it in the editor →

Take this with you

The address finds the machine; the port finds the program.

Go a little further

Add a reverse lookup, port_for(service), that returns the port for a service name.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →