SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • OSI Model
  • IP Address
  • TCP vs UDP
  • HTTP / HTTPS
  • DNS
  • Proxy vs Reverse Proxy
  • Checksums
  • HTTP/1.1 vs HTTP/2 vs HTTP/3
  • Cookies and CORS
  • Subnets, CIDR and NAT
  • Firewalls and VPN
  • Ports and Sockets
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Networking

Ports and Sockets

The door numbers on a machine, and the connections that pass through them.

โฑ 12 min readBeginnerMust KnowHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An IP address finds the right computer. A port finds the right program on that computer. A socket is one end of a live connection between two programs.

  • A port is a number from 0 to 65535. A web server listens on 443 (HTTPS), SSH on 22, PostgreSQL on 5432.
  • When your browser connects, the operating system gives it a temporary source port, so many connections can share one server port.
  • A connection is identified by five values: protocol, source IP, source port, destination IP and destination port.

02Concept: What is it?

One computer runs many network programs at once: a web server, a database, an SSH service, a mail program. When a packet arrives, the computer must decide which program should get it. The IP address only gets the packet to the machine. The port number picks the program.

A port is just a 16-bit number, so it goes from 0 to 65535. A program that wants to receive connections asks the operating system to listen on a port. Only one program can listen on a given port (and protocol) at a time on the same address. A second one gets an error such as "Address already in use".

A socket is the operating system's handle for one end of a network conversation. A server has a listening socket that waits for new clients. Each time a client connects, the server gets a new connected socket for that one client. The listening socket keeps waiting for the next one.

IP address, then port, then program
๐Ÿ“จPacketto 203.0.113.10 port 443
โ†’โ†“IP: find the machine
๐Ÿ–ฅ๏ธServer203.0.113.10
โ†’โ†“Port: find the program
๐ŸŒWeb serverport 443
๐Ÿ”‘SSHport 22
๐Ÿ—„๏ธDatabaseport 5432
The IP address finds the machine. The port finds the program. The same machine can run many programs.
๐Ÿง The five values
One connection is named by (protocol, source IP, source port, destination IP, destination port). The server side is the same for every client, so the client side (IP and port) is what makes each connection different.

03Real-Life Example

๐ŸตThe Office Building and Its Extension Numbers
A big office has one street address (the IP address) and one phone number at the front desk. Inside, each department has an extension: 22 for IT, 443 for customer service, 5432 for the records room. A caller dials the main number, then an extension. The receptionist connects them to the right desk. Customer service can talk to many callers at once. Each call gets its own line, and the phone system tells the calls apart by who is calling and from which line. Two departments cannot have the same extension.
Office phone system
Ports and sockets
The building's phone number
The IP address
An extension number
A port number
A department that answers calls
A program listening on a port
The receptionist waiting for calls
The listening socket
One active call with one caller
A connected socket
Two departments with the same extension
โ€œAddress already in useโ€
The caller's own line number
The client's source port
One listening socket, many connected sockets
๐Ÿ’ปLaptop198.51.100.10 : 50712
๐Ÿ“ฑPhone198.51.100.11 : 49310
โ†’โ†“to port 443
Server 203.0.113.10
๐Ÿ‘‚Listening socketport 443
๐Ÿ”—Connected 1to the laptop
๐Ÿ”—Connected 2to the phone
Server side (same port for everyone) Client side (own source port)

04Why Do We Need It?

๐ŸŽฏReach the right program
One machine runs many network programs. Ports let each one receive only its own traffic.
๐Ÿ‘ฅMany clients, one port
A web server serves thousands of users on port 443, because each connection has its own source address and port.
๐ŸงฉStandard doors
Well-known ports (80 for HTTP, 443 for HTTPS, 22 for SSH) let clients guess where to knock.
๐ŸงฑSimple rules for security
Firewalls allow or block by port. Open only the doors you need.
๐Ÿ”Debugging
Knowing ports and sockets helps you answer: is it listening? who is connected? is the port blocked?
โš–๏ธScaling limits
Every connection uses a socket and a port pair, so connection counts and port ranges become real limits.
The IP address finds the machine, the port finds the program, and the five values keep every connection separate.

05Where Do We Use It?

๐ŸŒWeb servers
Listen on 80 and 443. Every browser tab connects with its own source port.
๐Ÿ—„๏ธDatabases
PostgreSQL commonly uses 5432, MySQL 3306, Redis 6379. Apps connect to these ports.
๐Ÿ”‘Remote access
SSH uses port 22. Many teams limit who can reach it.
โš–๏ธLoad balancers
They accept connections on one port and open new connections to backends on other ports.
๐ŸงฑFirewalls and security groups
Rules such as โ€œallow TCP 443 from anywhere, allow 5432 only from the app serversโ€.
๐Ÿ“ฆContainers and Kubernetes
Containers map a container port to a host port. Services give a stable port in front of changing pods.

06Types / Parts / How It Works

Port ranges

RangeNameUse
0 to 1023Well-known portsStandard services: 80 (HTTP), 443 (HTTPS), 22 (SSH), 53 (DNS), 25 (SMTP). On many systems only privileged programs may listen here.
1024 to 49151Registered portsApplications registered by convention: 3306 (MySQL), 5432 (PostgreSQL), 6379 (Redis), 8080 (alternative HTTP).
49152 to 65535Dynamic or ephemeral portsTemporary source ports for clients (in the standard suggested range). Real systems may use a different range.

The two kinds of socket

Listening vs connected
Listening socket
๐Ÿ‘‚Waits on port 443
โ†“accept()
๐Ÿ†•New connected socket
Connected socket
โ†”๏ธReads and writes datafor one client only
๐Ÿ”’Closed when done
The listening socket never carries data. It only accepts new clients and hands each one a connected socket.

TCP and UDP have separate ports

TCP port 53 and UDP port 53 are different doors. DNS uses both. A program listening on TCP 8080 does not block another from using UDP 8080. See TCP vs UDP for how the two differ.

VisualizerOne server port, many clients: the five valuesAdd clients and connections and read each line. Then force every client to use the same source port, put all clients behind one IP, and start a second program on the same port.
Server listens on
Client addresses
Who picks the source port?
๐Ÿ–ฅ๏ธServer 203.0.113.10listening on port 443 (HTTPS web server)
Each line is one connection: protocol, source IP : source port โ†’ destination IP : destination port
LaptopTCP198.51.100.10:49152โ†’203.0.113.10:443
LaptopTCP198.51.100.10:50389โ†’203.0.113.10:443
PhoneTCP198.51.100.11:51626โ†’203.0.113.10:443
PhoneTCP198.51.100.11:52863โ†’203.0.113.10:443
TabletTCP198.51.100.12:54100โ†’203.0.113.10:443
TabletTCP198.51.100.12:55337โ†’203.0.113.10:443
Listening sockets
1
port 443
Connected sockets
6
one per connection
Server ports used
1
the same for everyone
Unique client ports
6
on the client side
One listening socket on port 443 serves every client. Each accepted connection is a separate connected socket, and the server side keeps using port 443 for all of them. The five values are what make each one unique.

A simplified picture. The addresses are from ranges reserved for examples. The ephemeral ports (49152 and above) come from a fixed formula, so the same settings always show the same ports. A real operating system may use a different range.

07How to Use It / Steps / Implementation

Working with ports in practice

  1. 1
    Pick the port on purpose
    Use the standard port for a standard service. For your own service choose one above 1024 and write it down in the config.
  2. 2
    Listen on the right address
    Listening on 127.0.0.1 means only this machine can connect. Listening on 0.0.0.0 means every network interface can. Use the second only when you mean it.
  3. 3
    Open only what you need
    In a firewall or cloud security group allow the ports your users need (often only 443) and keep databases on a private network.
  4. 4
    Let the OS choose client ports
    Do not hard-code a source port in a client. The operating system picks a free ephemeral port for each outgoing connection.
  5. 5
    Check what is listening
    On a Linux or macOS machine the tools ss, netstat or lsof show which program holds a port and which connections exist.
  6. 6
    Reuse connections
    Opening and closing many short connections burns ports and time. Use keep-alive and connection pools.
Useful commands (examples)
# who is listening on port 443?
sudo lsof -i :443
ss -ltnp | grep 443

# test whether a port is reachable
nc -vz example.com 443
๐Ÿ’กLocalhost versus everyone
A service that works on your laptop but is unreachable from another machine is often listening only on 127.0.0.1, or a firewall blocks the port.

08Key Terms to Know

TermMeaning in easy words
PortA number (0 to 65535) that picks a program on a machine
SocketOne end of a network conversation, as seen by the operating system
Listening socketA socket that waits for new clients on a port
Connected socketA socket for one live connection with one client
Well-known portA standard port for a common service, such as 80, 443 or 22
Ephemeral portA temporary source port the OS gives to an outgoing connection
Five-tupleProtocol, source IP, source port, destination IP and destination port. It names one connection
BindAsk the OS to attach a socket to an address and port
Port exhaustionA machine runs out of free source ports for new outgoing connections
TIME_WAITA short state after a TCP connection closes, when the OS keeps the port pair reserved so late packets cannot confuse a new connection
Address already in useThe error when another program already listens on that address and port

09Pros, Cons and Trade-offs

โœ… Pros
  • One machine can run many network services
  • Thousands of clients can share one server port
  • Standard ports make services easy to find
  • Port-based rules make firewalls simple
  • Sockets give programs a simple read and write interface
โš ๏ธ Cons
  • Only one listener per port and address
  • Ports and sockets are a limited resource
  • Wrong or too many open ports widen the attack surface
  • Port-based rules say little about what the traffic really is
  • Many short connections waste ports and CPU

Trade-offs

ChoiceWe gainWe lose
Standard port (443)Clients and firewalls just workScanners and attackers know where to look
Custom portAvoids clashes, hides from casual scansMust be documented, and some networks block unusual ports
Listen on 0.0.0.0Reachable from other machinesExposed to every network the host is on
Listen on 127.0.0.1Safe: only local programs connectNot reachable from outside
Many short connectionsSimple codeMore ports used, more handshakes, more TIME_WAIT
Reused (keep-alive) connectionsFewer ports, faster requestsIdle connections hold resources and need timeouts

10Common Problems and Mistakes

Common mistakes

  1. "Address already in use". An old copy of the program still runs, or another service owns the port. Find the owner before changing the port.
  2. Exposing a database port to the world. Port 5432 or 6379 open to the internet is a common cause of breaches.
  3. Listening on the wrong address. Bound to 127.0.0.1 inside a container, so nothing outside can connect.
  4. Hard-coding client source ports. A second connection to the same server fails because the five values clash.
  5. Forgetting the firewall. The program listens fine, yet the cloud security group blocks the port.
  6. Running out of ephemeral ports. A proxy or client that opens huge numbers of short connections to one destination can use up its source ports.
  7. Mixing up TCP and UDP rules. Opening TCP 53 does not open UDP 53.

Things to watch

โณTIME_WAIT pile-up
Many closed connections wait briefly. Reuse connections to keep the count low.
๐ŸงฎOpen file limits
On Linux each socket uses a file descriptor. A low limit stops new connections long before the CPU is busy.
๐Ÿ”€NAT port sharing
Many clients behind one public IP share its port range. A NAT device can run out of ports too.
๐Ÿ›ฐ๏ธPort scans
Attackers probe for open ports. Close what you do not use.

11Real-World Examples

๐Ÿ›’Online shops
Millions of browsers connect to port 443 of the same few load balancers. The source ports tell the connections apart.
๐Ÿ—„๏ธApp to database
An app server opens a pool of connections to port 5432. Each one has its own source port on the app side.
๐Ÿ Home routers (NAT)
A whole household shares one public IP. The router remembers which source port belongs to which device.
๐Ÿ“ฆDocker
A flag such as -p 8080:80 maps host port 8080 to container port 80.
๐Ÿ”Cloud security groups
Teams allow 443 from the internet and 5432 only from the app subnet.
๐Ÿ•ต๏ธDebugging outages
โ€œIs the port open? Who is listening? Is the connection count at its limit?โ€ are the first questions.
๐Ÿ“Note
Port numbers for products are defaults. Teams change them, so always check the configuration of the system you work on.
Mini case: three apps behind one public IP
๐Ÿ’ปLaptop192.168.1.5 : 50000
๐Ÿ“ฑPhone192.168.1.6 : 50000
โ†’โ†“NAT
๐Ÿ“กRouterpublic IP, ports 40001 and 40002
โ†’โ†“to port 443
๐ŸŒWeb server
The router (NAT) rewrites source ports, so replies find the right device.

12Related Topics to Read Next

IP Addressโ†’

The address that finds the machine before the port finds the program.

TCP vs UDPโ†’

Both use ports, but ports are separate for each protocol.

Subnets, CIDR and NATโ†’

NAT shares one public IP by rewriting source ports.

Firewalls and VPNโ†’

Firewalls allow or block traffic by port.

OSI Modelโ†’

Ports live at the transport layer (Layer 4).

Layer 4 vs Layer 7 Load Balancersโ†’

Layer 4 balancers decide using IP addresses and ports.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Port: 0 to 65535. Picks the program on a machine.
  • โœ”Well-known: 80 HTTP, 443 HTTPS, 22 SSH, 53 DNS, 5432 PostgreSQL.
  • โœ”Socket: one end of a connection. Listening socket accepts, connected socket carries data.
  • โœ”Five values: protocol, source IP, source port, destination IP, destination port.
  • โœ”One server port, many clients: the source side makes each connection unique.
  • โœ”Ephemeral ports: the OS picks them. Never hard-code a client source port.
  • โœ”Common errors: address already in use, port blocked by a firewall, listening on 127.0.0.1 only.
  • โœ”One line: โ€œThe IP finds the machine, the port finds the program, the five values keep every connection apart.โ€
โ† Previous
Firewalls and VPN
Next โ†’
What are Load Balancers?