Computer Network
Ports and Sockets

Ports and Sockets

When an operating system receives a network packet, how does it know which application to send it to? The computer might be running a web browser, a database server, a background chat client, and an email app simultaneously.

The answer is Transport Layer Multiplexing using Ports and Sockets.


1. What is a Port? What is a Socket?

  • Port: A logical 16-bit identifier (representing numbers from 0 to 65535) associated with a network connection. It separates communication channels on the same device.
  • Socket: The software abstraction representing an endpoint for sending or receiving data. A socket is bound to a specific IP address and Port.
       +---------------------------------------------+
       |               Operating System              |
       |                                             |
       |  [ Application A ]       [ Application B ]  |
       |          |                      |           |
       |      Socket 1                Socket 2       |
       |   (127.0.0.1:80)         (127.0.0.1:5432)   |
       +----------+----------------------+-----------+
                  |                      |
                  +----------+-----------+
                             |
                      Network Interface

The 5-Tuple Connection Unique Key

Connection ID = { Source IP, Source Port, Destination IP, Destination Port, Protocol }

Because of this 5-tuple uniqueness, a server listening on a single port (like port 443 for HTTPS) can handle hundreds of thousands of concurrent connections from different clients.


2. Port Ranges

The Internet Assigned Numbers Authority (IANA) divides ports into three ranges:

RangeTypeDescriptionExamples
0 – 1023Well-Known PortsReserved for core system services and common protocols. On Unix-like systems, binding to these ports requires superuser privileges (root).22 (SSH), 53 (DNS), 80 (HTTP), 443 (HTTPS)
1024 – 49151Registered PortsAssigned by IANA to specific services, database software, or application servers. User processes can run on these ports.3306 (MySQL), 5432 (PostgreSQL), 6379 (Redis), 8080 (Alternative Web Server)
49152 – 65535Dynamic / Ephemeral PortsTemporary ports allocated automatically by the OS client-side when initiating an outbound connection.Assigned dynamically to outbound requests from your web browser.

3. TCP vs. UDP Ports

Though TCP and UDP run over the same IP network layer, their port spaces are entirely separate.

  • TCP Ports: Establish connection state, enforce reliability, order delivery, and perform flow control (e.g., TCP port 80).
  • UDP Ports: Connectionless, thin-wrapper over IP. They send fire-and-forget datagrams with minimal overhead (e.g., UDP port 53 for DNS, or Port 123 for NTP).
  • An application can bind to both TCP 53 and UDP 53 concurrently without collision.

4. Crucial Ports Reference for Developers

Here are the standard ports every software engineer should recognize instantly:

PortProtocolCommon Name / Usage
22TCPSSH (Secure Shell) & SFTP
25TCPSMTP (Simple Mail Transfer Protocol - server-to-server)
53TCP/UDPDNS (Domain Name System queries)
80TCPHTTP (Hypertext Transfer Protocol - unencrypted web)
123UDPNTP (Network Time Protocol - clock synchronization)
443TCPHTTPS (Hypertext Transfer Protocol Secure - SSL/TLS encrypted)
3306TCPMySQL database
5432TCPPostgreSQL database
6379TCPRedis cache / key-value store
27017TCPMongoDB database

5. OS Socket States (TCP)

When debugging performance or networking bugs on Linux/Mac, understanding TCP socket states is critical:

  • LISTEN: The server socket is waiting for an incoming connection request from a client.
  • SYN_SENT / SYN_RECEIVED: Part of the TCP 3-way handshake. The connection is being set up.
  • ESTABLISHED: The connection is active. Data can be sent and received.
  • CLOSE_WAIT: The remote host has closed its end of the connection, and the local OS is waiting for the local application to call close() on the socket. (A high number of sockets in CLOSE_WAIT indicates an application-level resource leak).
  • TIME_WAIT: The local endpoint closed the connection first, and is waiting in a safety buffer state (usually 1-4 minutes) to ensure any delayed packets in flight are discarded. (High TIME_WAIT count can cause ephemeral port exhaustion under heavy traffic loads).

6. Practical CLI Commands for Port Debugging

1. lsof (List Open Files)

On Unix/macOS, sockets are treated as files. lsof helps find what process is running on a port.

# Find which process is listening on Port 8080
lsof -i :8080
 
# Show established network connections
lsof -i -P -n | grep ESTABLISHED

Note: Flags -P inhibits translation of port numbers to names, and -n inhibits translation of IP addresses to hostnames.

2. ss and netstat (Socket Statistics)

Modern Linux uses ss (Socket Statistics) to inspect socket states. Mac users use netstat.

# Linux: List all TCP sockets in listening state with process IDs
ss -ltnp
 
# macOS: List all listening sockets
netstat -an | grep LISTEN

Flags analysis for ss:

  • -l: Show listening sockets
  • -t: Show TCP sockets
  • -n: Show numeric port numbers (don't resolve to service names)
  • -p: Show process utilizing the socket (requires sudo)

3. Testing Connectivity with nc (Netcat) and telnet

Before writing code, test raw socket connectivity to verify firewalls or security groups are not blocking ports.

# Connect to port 443 on github.com via telnet
telnet github.com 443
 
# Check if port 5432 is open using netcat (zero-I/O mode)
nc -zv 127.0.0.1 5432

If successful, you will see a Connection to [IP] port [PORT] [tcp/...] succeeded! message.