What is a computer network, including LAN, MAN, WAN, and PAN types?
KnownRevise
A computer network is a collection of interconnected computing devices that exchange data and share resources using communication links and common protocols. Networks are commonly classified by their geographic and operational scope into PAN, LAN, MAN, and WAN.
Read full answerHide full answer
Applies tocomputer networking (general concepts, OSI and TCP/IP models)
Main Network Types
Type
Typical scope
Common technologies
Typical example
PAN — Personal Area Network
Very small area around one person or device, usually measured in meters
Bluetooth, NFC, Zigbee, infrared
A smartphone connected to headphones and a smartwatch
LAN — Local Area Network
Building, office, home, or campus
Ethernet, Wi-Fi, VLANs
Employees accessing file and application servers in an office
MAN — Metropolitan Area Network
Multiple sites across a city or metropolitan region
Metro Ethernet, fiber, MPLS
University campuses connected across one city
WAN — Wide Area Network
Large geographic areas, potentially spanning countries or continents
A company connecting offices in different countries
These categories describe scale rather than a strict protocol boundary. A single organization can operate a LAN internally and connect its locations through a WAN. A WAN may be privately managed or provided by a telecommunications carrier.
The Internet is a global interconnection of many independently administered networks. It is therefore best viewed as a network of networks rather than one centrally owned LAN or WAN.
How a Network Communicates
The OSI model and the TCP/IP model describe how communication responsibilities are divided:
OSI layer
Common TCP/IP layer
Networking responsibility
Application, Presentation, Session
Application
HTTP, DNS, SMTP, TLS, and application data
Transport
Transport
TCP reliability or UDP low-overhead delivery
Network
Internet
IP addressing, packet forwarding, and routing
Data Link, Physical
Network Access
Frames, MAC addressing, media access, and physical signals
For example, when a browser requests a web page:
DNS resolves the destination domain name into an IP address.
The client creates a TCP connection, or a QUIC connection over UDP, to the server.
The destination IP address is placed in an IP packet.
The packet is encapsulated in a link-layer frame for transmission across the local network.
Routers forward the packet toward the destination network.
The receiving host verifies and processes the packet before delivering the response.
Textbooks show these boundaries as strict layers. Real systems, such as the Linux TCP/IP stack, are conceptually layered but often combine functions for efficiency. For example, network-interface drivers handle parts of both the physical and data-link layers, while high-speed networking may use checksum offload and other hardware optimizations.
Components and Topologies
A network commonly consists of:
End hosts: computers, servers, phones, sensors, and IoT devices.
Network interface cards: controllers that connect devices to a medium.
Switches: devices that forward Ethernet frames using MAC addresses.
Routers: devices that forward IP packets between different networks.
Wireless access points: devices that provide Wi-Fi connectivity.
Transmission media: twisted-pair cable, coaxial cable, fiber-optic cable, or radio waves.
Protocols and services: rules such as IP, TCP, UDP, HTTP, and DNS.
Physical topology describes how links are arranged. A star, commonly used with Ethernet, has each host connected to a central switch. A mesh provides multiple paths and is highly resilient, but it requires more links and coordination. A bus is inexpensive but suffers from shared-medium and collision-related limitations on traditional Ethernet.
Concrete Example
Suppose a laptop has the private IPv4 address 192.168.1.20 and connects through a home router with address 192.168.1.1.
The laptop and router form a LAN.
The laptop’s Ethernet or Wi-Fi connection provides the local physical and data-link links.
The router separates the private LAN from its upstream WAN connection.
When the laptop contacts a remote server, it sends the packet to its default gateway rather than directly to the remote host.
The router, often combined with NAT, forwards traffic through the ISP’s network.
Routers across the Internet route the packet to the destination network.
The private address 192.168.1.20 is not globally routable on the Internet. NAT translates traffic originating behind the router, while stateful firewalls commonly track active connections.
Trade-offs and Practical Guidance
Design concern
Trade-off
Geographic scale
Larger networks support more distance and users but usually introduce higher latency and cost
Ownership
Private networks provide more control but require the organization to manage equipment and connectivity
Redundancy
Multiple paths improve availability but add cost and routing complexity
Security
A LAN may be physically isolated but is still vulnerable to compromised hosts, weak credentials, and misconfiguration
Performance
Higher bandwidth increases capacity, but congestion, latency, packet loss, and protocol overhead still affect user experience
Network type alone does not guarantee security. Practical systems use authentication, encryption, firewall rules, VLAN segmentation, access control, monitoring, and secure configuration. Campus and interview candidates can inspect a network with tools such as ip addr, ip route, ss, ping, traceroute, dig, curl, and tcpdump. The most important distinction is that LAN, MAN, WAN, and PAN describe network scale, while OSI and TCP/IP describe how communication functions are organized.
2
What are the seven layers of the OSI model?
KnownRevise
The OSI model is a seven-layer reference framework that separates networking responsibilities into abstraction layers. Each layer provides services to the layer above while using services from the layer below; data is progressively encapsulated as it moves down the stack and decapsulated at the destination.
Read full answerHide full answer
Applies toOSI reference model and TCP/IP stacks (all versions)
The Seven Layers
Layer
Main function
Typical protocols or technologies
Data unit
7. Application
Provides network services directly to applications
HTTP, DNS, SMTP, DHCP
Data
6. Presentation
Handles data representation, encoding, compression, and encryption
TLS, ASCII, UTF-8, JPEG
Data
5. Session
Establishes, manages, synchronizes, and terminates sessions
RPC, NetBIOS
Data
4. Transport
Provides end-to-end communication, segmentation, port addressing, reliability, and flow control
TCP, UDP
Segment or datagram
3. Network
Provides logical addressing, routing, and packet forwarding across networks
IP, ICMP, routers
Packet
2. Data Link
Provides local-link framing, MAC addressing, error detection, and media access control
Ethernet, Wi-Fi, PPP
Frame
1. Physical
Transmits raw bits as electrical, optical, or radio signals
Ethernet cables, fiber, radio
Bits
Layer-by-Layer Responsibilities
Application layer: Defines how applications exchange network data. For example, a browser sends an HTTP request, while dig sends a DNS query. It does not normally control how bits physically reach the destination.
Presentation layer: Converts application data into a suitable representation. This includes character encoding, serialization, compression, and encryption. TLS is commonly associated with this layer, although its handshake ultimately uses transport-layer connections.
Session layer: Maintains conversational state between applications, including session establishment, synchronization, and recovery. Modern applications often implement these responsibilities within application libraries or protocols.
Transport layer: Delivers data between host processes through port-numbered transport endpoints. TCP provides reliable, ordered delivery with acknowledgments, retransmissions, flow control, and congestion control. UDP provides connectionless delivery without those guarantees.
Network layer: Routes packets between networks using logical IP addresses. Routers make forwarding decisions at this layer. IP provides best-effort delivery; protocols such as ICMP report errors and diagnostics.
Data Link layer: Moves frames across a single local network. Ethernet uses MAC addresses and frame checksums to detect transmission errors. Switches primarily operate at this layer.
Physical layer: Sends and receives bits over physical media. It defines signal levels, voltage or optical characteristics, connectors, transmission rates, and media standards.
Encapsulation and Decapsulation
When an application sends data, the operating system normally adds headers as the data travels downward:
The transport layer adds a TCP header or UDP header, creating a segment or datagram.
The network layer adds an IP header, creating a packet.
The data link layer adds a link-layer header and trailer, creating a frame.
The physical layer transmits the frame’s bits over the medium.
The receiver performs the reverse process. This modular design lets an application use HTTP without knowing whether the packet crosses Ethernet, Wi-Fi, fiber, or an IP-based core network.
Real Systems Versus the Textbook Model
The OSI model is primarily a teaching and conceptual reference; production TCP/IP stacks rarely implement all seven layers as distinct subsystems.
OSI layers
Common TCP/IP mapping
Application, Presentation, Session
Application layer
Transport
Transport layer
Network
Internet layer
Data Link, Physical
Network access or link layer
Linux combines several OSI responsibilities. The kernel’s TCP/IP networking stack handles sockets, transport protocols, IP routing, and link-layer interfaces, while Ethernet framing is commonly processed by device drivers and network interface controllers. TLS is usually implemented in user-space libraries, but from a protocol perspective it secures data carried by an underlying transport connection.
Interview Takeaways
Remember the order: Application, Presentation, Session, Transport, Network, Data Link, Physical.
Distinguish addressing: MAC addresses identify interfaces on a local link; IP addresses identify network interfaces across interconnected networks; port numbers identify transport-layer endpoints, usually associated with an application or service, on a host.
Distinguish delivery guarantees: IP is best-effort, UDP is connectionless, and TCP provides reliable, ordered byte delivery.
Avoid assuming strict layer separation: OSI is a reference model, while real protocols often span or combine adjacent layers.
3
How does the OSI model differ from the TCP/IP model?
KnownRevise
The OSI model is a seven-layer conceptual framework for organizing network communication, while the TCP/IP model is a more practical four-layer model describing how Internet protocols operate. OSI is useful for teaching and troubleshooting; TCP/IP better reflects deployed Internet systems.
Read full answerHide full answer
Applies tocomputer networks (OSI reference model and TCP/IP protocol suite)
Models at a Glance
The OSI model, defined by ISO, separates networking into seven layers. Each layer provides services to the layer above and uses services from the layer below.
The TCP/IP model groups several OSI responsibilities into broader layers. It is closely aligned with the architecture of the Internet and contains protocols such as TCP, UDP, IP, HTTP, and DNS.
OSI layer
Responsibility
Typical TCP/IP layer
Application
Network services available to applications
Application
Presentation
Data formatting, encoding, compression, encryption
Application
Session
Establishing, managing, and terminating sessions
Application
Transport
End-to-end delivery, reliability, flow control, congestion control
Transport
Network
Logical addressing, routing, packet forwarding
Internet
Data Link
Framing, MAC addressing, link-level error detection
Network Access
Physical
Transmission of raw bits over a medium
Network Access
Some textbooks use a five-layer TCP/IP model, separating the Network Access layer into Data Link and Physical layers. This hybrid is convenient for teaching but is not the usual four-layer Internet model.
What Each Layer Does
OSI Application layer: Defines services directly used by applications, such as file transfer, email, and web access.
OSI Presentation layer: Handles representation and security of application data, including serialization and encryption.
OSI Session layer: Controls dialogue between applications, including session establishment and synchronization.
OSI Transport layer: Provides host-to-host communication, segmentation, reliability, and flow control.
OSI Network layer: Routes packets between networks using logical addresses such as IPv4 and IPv6 addresses.
OSI Data Link layer: Moves frames across one physical link and uses MAC addresses for local delivery.
OSI Physical layer: Transmits bits as electrical, optical, or radio signals.
TCP/IP Application layer: Combines application, presentation, and session functions. It includes HTTP, DNS, DHCP, SMTP, and TLS.
TCP/IP Transport layer: Implements TCP or UDP. TCP provides reliable, ordered byte delivery; UDP provides connectionless delivery with minimal overhead.
TCP/IP Internet layer: Uses IP for addressing and routing. It also includes ICMP for diagnostics and control messages.
TCP/IP Network Access layer: Handles frames, MAC addressing, media access, and the physical transmission of bits.
Example: Loading an HTTPS Page
When a client requests https://example.com:
The browser uses DNS, normally over UDP, to obtain the server’s IP address.
TLS establishes encryption and negotiates cryptographic parameters.
TCP creates a connection and provides reliable, ordered delivery between the client and server.
IP routes the resulting packets through the Internet.
At each local network, Ethernet or another link-layer technology carries frames using MAC addresses.
The physical medium transmits the bits, which the receiver converts back into frames, packets, segments, and application data.
In this example, OSI layers remain useful conceptual categories even though real implementations often combine them.
Key Differences
Aspect
OSI model
TCP/IP model
Structure
Seven layers
Usually four layers; sometimes five in textbooks
Origin
ISO reference model
Developed from the practical Internet protocol suite
Primary purpose
Standardized conceptual framework
Describes real Internet communication
Layer boundaries
Strictly separated responsibilities
Groups related OSI functions together
Session and presentation
Explicit layers
Included in the Application layer
Physical and data link
Separate layers
Combined into Network Access
Protocol independence
Can describe many networking technologies
Closely tied to TCP, UDP, IP, and Internet protocols
Common use
Teaching, troubleshooting, and communication
Networking implementation and Internet administration
Real Systems and Trade-Offs
Real operating-system stacks do not always implement a strict layer boundary for every protocol. For example, Linux uses the kernel’s TCP/IP stack, but applications normally access networking through sockets rather than separate session or presentation APIs. TLS is commonly implemented in user space or through libraries, even though it logically sits above TCP and below HTTP.
OSI’s separation improves modularity and makes failures easier to classify: a DNS issue is an application-layer problem, while an unreachable destination may be a routing problem. TCP/IP is more directly applicable to the Internet but gives less detail for discussing sessions, formatting, and physical signaling. Interview candidates should therefore know both the seven OSI layers and the four-layer TCP/IP mapping, while recognizing that the five-layer version is also common in academic settings.
4
What are network topologies and their advantages and disadvantages?
KnownRevise
A network topology is the arrangement of nodes and links in a computer network. It describes how devices connect and how data moves, and can be considered at the physical layer for cable layout or the logical layer for actual communication paths.
Read full answerHide full answer
Applies tocomputer networks and the OSI physical and data link layers
Physical and Logical Topologies
A topology may be classified in two ways:
Physical topology: The visible arrangement of devices, cables, and connection points.
Logical topology: The path followed by data, regardless of the physical wiring.
For example, devices may be physically wired in a star but communicate through a switched Ethernet bus-like logical network. Modern switched LANs are often described physically as stars because each host connects to a switch, while the switch forwards frames according to MAC addresses.
Common Topologies
Topology
How it works
Advantages
Disadvantages
Bus
All devices share one main communication line.
Simple and inexpensive for a small network.
A cable or repeater failure can disrupt the network; collisions become difficult as traffic increases.
Star
Each device connects to a central hub or switch.
Easy to install, diagnose, and expand; one link failure usually affects only one device.
Requires more cabling; the central device is a single point of failure if it fails.
Ring
Each device connects to two neighbors, forming a closed loop.
Data travels in an orderly direction and can be managed predictably.
A link or node failure may disrupt the ring unless dual-ring or bypass mechanisms are used.
Mesh
Devices connect to many or all other devices.
High availability, fault tolerance, and performance because traffic has multiple possible paths.
Expensive and complex because it requires many links, ports, and configuration effort.
Tree
Star or bus networks are connected in a hierarchical structure.
Scalable and suitable for large networks; supports segmentation.
Failure of an upper-level device can disconnect entire branches.
Hybrid
Different topologies are combined.
Fits real organizational and technical requirements.
More expensive to design, configure, maintain, and troubleshoot.
Point-to-point
Two endpoints have a dedicated link.
Predictable performance, simpler traffic behavior, and isolation between segments.
Does not scale directly to many hosts without additional links or switching equipment.
How the Textbook Model Differs from Real Systems
The diagrams in textbooks represent network organization clearly, but real implementations often combine several models:
Ethernet LANs: A physical star around a switch are common. The switch creates separate collision domains per port, unlike an old Ethernet hub, where all ports shared one collision domain.
Wi-Fi: A wireless access point creates a star-like arrangement, but the radio medium is shared. Wi-Fi therefore still has contention and cannot provide the same collision-free behavior as each device having a dedicated Ethernet link.
Internetworked LANs: A company may use a hierarchical tree of routers, local switched stars, and point-to-point WAN links rather than one pure topology.
Mesh networking: Wireless mesh networks can provide multiple forwarding paths without every node having a physical connection to every other node.
Example: Star Topology
Suppose eight computers connect to one Ethernet switch:
The physical topology is a star.
A switch forwards frames only toward the destination port when it knows the MAC address.
Each switch port is a separate collision domain and normally has its own bandwidth.
If one computer’s cable fails, the other seven computers remain connected.
If the switch fails, the entire local segment becomes unavailable, so redundant switches or alternate paths may be needed for high availability.
This example demonstrates the main star-topology trade-off: inexpensive per-host connectivity and easy fault isolation, but dependence on the central aggregation point.
Selection Criteria and Best Practices
When selecting a topology, consider:
Scalability: How many devices must the network support initially and later?
Reliability: What happens when a cable, node, or central device fails?
Performance: Is the workload local, heavily broadcast-based, or distributed across WAN links?
Cost: Include cabling, switches, ports, configuration, and maintenance—not only hardware.
Security and segmentation: VLANs, subnets, firewalls, and access controls can limit traffic between network areas.
Management: A structured topology makes monitoring and troubleshooting easier.
For most enterprise LANs, a hierarchical switched-star design is more practical than a pure bus, ring, or full mesh. Use redundancy for critical links, segment traffic with VLANs and IP subnets, and treat the physical drawing as only one part of the network’s logical and security design.
5
How do hubs, switches, and routers differ in networking?
KnownRevise
A hub, switch, and router operate at different layers of the networking stack: a hub repeats electrical signals, a switch forwards Ethernet frames using MAC addresses, and a router forwards IP packets between networks. They also differ in collision domains, broadcast behavior, and supported traffic.
Read full answerHide full answer
Applies tocomputer networking (Ethernet and IPv4/IPv6; all versions)
OSI and TCP/IP Responsibilities
Device
Typical OSI layer
Primary address
Main function
Hub
Layer 1 — Physical
None
Regenerates and repeats incoming bits to every other port
Switch
Layer 2 — Data Link
MAC address
Learns MAC addresses and forwards frames selectively
Router
Layer 3 — Network
IP address
Connects different networks and chooses routes for packets
In the TCP/IP model, these correspond approximately to the network interface layer, network interface layer, and internet layer, respectively. The OSI model remains useful for explaining their distinct responsibilities.
Hub: Physical-Layer Repeater
A hub has no intelligence about addresses, frames, or packets. When a signal arrives on one port, it repeats that signal out through all other ports.
Collision domain: All ports share one collision domain.
Broadcast domain: All ports also share one broadcast domain.
Bandwidth: Each device consumes the hub’s shared available bandwidth.
Duplex operation: Hubs generally operate in half-duplex mode because multiple stations may transmit simultaneously.
Modern relevance: Hubs are largely obsolete. Repeaters also exist in specialized cabling systems, but ordinary Ethernet deployments use switches.
For example, if four computers connect to a hub, a frame transmitted by one computer can be received by the other three. All four stations also compete for the same transmission medium.
Switch: Layer-2 Frame Forwarding
A switch learns the source MAC address of each arriving frame and associates it with the port on which it arrived. It maintains a MAC address table, also called a forwarding table, to decide where to send outgoing frames.
Collision domain: Each switch port normally has a separate collision domain.
Broadcast domain: All ports normally remain in one broadcast domain unless VLANs are configured.
Duplex operation: Modern switches normally support full-duplex connections, allowing simultaneous sending and receiving without collisions.
Unknown destinations: If the destination MAC is unknown, the switch floods the frame within the relevant VLAN.
Managed features: VLANs, link aggregation, port security, and sometimes Layer-3 switching can be configured on advanced switches.
A Layer-2 switch forwards an Ethernet frame without normally examining the enclosed IP address. For example, a laptop sends a frame to the printer’s MAC address; the switch forwards it only through the printer’s port.
Router: Layer-3 Packet Forwarding
A router connects separate IP networks and forwards packets based on destination IP addresses. It uses a routing table containing destination prefixes and information about the next hop.
Collision domains: Each routed interface is normally a separate collision domain.
Broadcast domains: Routers do not forward Layer-2 broadcasts by default, so each routed interface normally belongs to a separate broadcast domain.
Packet processing: The router selects an outgoing interface, decrements the IPv4 TTL or IPv6 Hop Limit, and encapsulates the packet in a new frame for the next link.
Suppose a host with 192.168.1.10/24 wants to reach 192.168.1.20/24. Because the destination is on the same subnet, it resolves the destination’s MAC address using ARP and sends the Ethernet frame directly through the switch. To reach 8.8.8.8, it instead resolves and sends the frame to the default gateway’s local MAC address; the router then forwards the IP packet toward the destination network.
Key Trade-Offs and Modern Systems
Cost and complexity: Hubs are simple but inefficient; switches are standard for local networks; routers provide inter-network communication.
Broadcast control: VLANs can divide a switch into separate broadcast domains, while routing connects those domains.
Converged devices: Many enterprise switches support Layer-3 routing, and many home routers combine switching, routing, Wi-Fi access point functionality, NAT, firewalling, and DHCP.
Linux implementation: The Linux kernel supports software Layer-2 bridges. A bridge can be created with ip link add name br0 type bridge, while ip route manages the kernel’s Layer-3 routing table. These features model the same conceptual separation as physical switches and routers.
The key distinction is therefore not merely physical design: hubs repeat signals, switches make forwarding decisions using MAC addresses, and routers make forwarding decisions using IP prefixes and routing tables.
6
How do bridges, gateways, and modems differ?
KnownRevise
A bridge connects LAN segments at the data link layer, a gateway connects networks or translates between incompatible systems, and a modem converts data into signals suitable for a communication channel. Their names sometimes overlap in real networks, but they perform fundamentally different functions.
Read full answerHide full answer
Applies tocomputer networks (OSI and TCP/IP models)
Primary Functions
Device
Primary role
Typical OSI layer
Real-world example
Bridge
Forwards Ethernet frames between LAN segments using MAC addresses
Data link layer (Layer 2)
Linking two Ethernet LANs
Gateway
Connects networks or translates between different protocols and application formats
Network through application layers
A router serving as a home network’s default gateway
Modem
Converts digital data into channel-compatible signals and converts received signals back into data
Physical layer (Layer 1)
A DSL or cable Internet modem
Bridges
A bridge maintains a table associating each MAC address with the port on which it was observed. When it receives a frame, it forwards it only to the destination port if the destination is on another segment. If the destination is unknown, it may flood the frame across the other ports until it learns the address.
Learning bridge: Builds its forwarding table dynamically from source MAC addresses.
Transparent bridge: Makes connected devices behave as though they share one LAN.
Spanning Tree Protocol (STP): Prevents loops when multiple bridges create redundant paths.
Broadcast domain: A bridge does not normally separate broadcast domains; routers do.
Collision domain: Separate bridge ports generally create separate collision domains.
In modern networking, most multiport bridges are implemented as switches. A switch is therefore commonly described as a multiport bridge with specialized forwarding hardware.
Gateways
“Gateway” has two related meanings:
Default gateway: The router interface through which a host sends packets destined for another network. It routes traffic based on IP addresses. For example, 192.168.1.1 is commonly the default gateway for a home LAN.
Protocol or application gateway: A system that connects incompatible systems and translates data between them. Examples include an email gateway, a protocol converter, or a web application gateway that exposes HTTP services to other applications.
A router does not normally translate the payload of an IP packet. It selects the next network and forwards the packet. An application gateway may inspect or modify the application payload, but doing so adds processing overhead and can introduce security risks.
Modems
A traditional modem performs modulation and demodulation:
Modulation: Converts digital bits into an analog carrier signal.
Demodulation: Converts the received analog signal back into digital bits.
A telephone-line modem, for example, encodes digital data onto an audible carrier signal. Cable and fiber-optic modems also convert between digital Ethernet data and electrical or optical signals, but these are not usually described as analog modems in the traditional sense.
A modem normally provides a physical-layer connection; it does not decide where packets should be routed. A home “cable modem,” for example, may appear as one box while internally including modem, routing, Ethernet-switching, wireless, and network-management functions.
Worked Example
Suppose a laptop sends a request to a server on the Internet:
The laptop compares the destination IP address with its local subnet.
If the server is outside the local subnet, the laptop sends the packet to its default gateway, usually a router.
The router forwards the packet across the ISP’s network.
If the ISP connection uses DSL, a modem converts the traffic between the router’s digital interface and the carrier’s transmission medium.
A bridge or switch may connect Ethernet devices within a LAN, forwarding frames according to MAC addresses.
Trade-offs and Common Confusions
Bridge versus switch: A switch is usually a multiport Layer 2 bridge, often with additional management features.
Gateway versus router: “Default gateway” usually means a router, while “application gateway” usually performs translation or policy enforcement.
Modem versus router: A modem provides WAN connectivity and signal conversion; a router chooses IP paths and often also provides NAT, firewalling, and DHCP.
Bridge versus router: A bridge forwards frames within related LANs, whereas a router moves packets between separate IP networks.
7
What distinguishes circuit switching from packet switching?
KnownRevise
Circuit switching reserves a dedicated end-to-end path for the entire communication session, while packet switching divides data into independently routed packets that share network resources statistically. Both approaches exist in real networks, although modern Internet communication primarily uses packet switching.
Read full answerHide full answer
Applies tocomputer networks (OSI and TCP/IP models)
Core Differences
Aspect
Circuit switching
Packet switching
Resource allocation
Dedicated resources are reserved for the session
Resources are shared dynamically
Data representation
Continuous stream over an established path
Messages split into discrete packets
Setup
A connection must be established before data transfer
No connection setup is inherently required
Path
Usually remains fixed for the session
Each packet may take a different path
Bandwidth
Fixed or guaranteed once established
Variable and allocated according to demand
Delay
Low and predictable after setup
Variable because of queuing and routing
Failure handling
Failure along the path can terminate the session
Packets can be rerouted around failures
Congestion
Less likely because capacity is reserved
Can cause queuing delay, packet loss, and retransmission
Overhead
Setup cost and potentially idle capacity
Headers and per-packet processing
Typical use
Traditional telephone networks
IP-based Internet, Ethernet, Wi-Fi
How Circuit Switching Works
A circuit-switched network first establishes a dedicated path between the source and destination. Resources such as time slots, frequencies, or transmission capacity are reserved along that path.
For example, in the traditional public switched telephone network, the exchange selects a route and reserves capacity for the call. Once the connection is established:
The caller receives a fixed amount of bandwidth.
Data arrives in order because it follows one path.
The reserved capacity remains available even during silence.
Breaking a link on the path usually interrupts the connection.
Circuit switching provides predictable delay and makes real-time voice communication straightforward. Its main disadvantage is inefficient resource use: bandwidth reserved for a pause in conversation cannot immediately be assigned to another session.
How Packet Switching Works
A packet-switched network divides application data into smaller units called packets. Each packet contains a header with source and destination addresses and other control information.
Routers examine the packet headers and forward packets independently. This is known as store-and-forward switching: a router usually receives a complete packet before forwarding it to the next hop.
Because packets from multiple sessions share links:
Available bandwidth is allocated dynamically.
A router may prioritize packets based on application or service requirements.
Packets can take different routes and arrive out of order.
Congestion may cause packets to wait in queues or be dropped.
Transport-layer protocols such as TCP detect loss and retransmit missing data.
IP is the dominant packet-switching technology. Ethernet and Wi-Fi provide packet-based access to IP networks, while TCP or UDP manages reliable or connectionless delivery over IP.
Example and Trade-Offs
Suppose two users make a voice call:
In a circuit-switched telephone network, the network reserves a fixed path for the call. The call has consistent bandwidth and predictable delay, but unused capacity cannot serve other users.
In a packet-switched VoIP system, encoded voice is carried in IP packets. Network capacity is used only when packets are transmitted, making the system efficient for bursty traffic. However, congestion can introduce delay or loss, so the application may use buffering, jitter control, and packet-loss concealment.
Packet switching generally scales better and tolerates failures more effectively. Circuit switching can still be advantageous when guaranteed capacity and extremely predictable timing are more important than efficient resource utilization.
Real-World Hybrid Systems
Real networks are not always purely one model or the other:
MPLS uses packet switching but can reserve traffic-engineering resources for particular flows.
ATM combines cell switching with virtual-circuit concepts.
Carrier Ethernet can provide virtual connections resembling dedicated circuits over a packet-switched infrastructure.
Circuit emulation carries legacy circuit traffic across packet networks using additional adaptation and buffering.
Thus, the textbook distinction remains useful, but modern carrier networks often combine statistical multiplexing with controlled resource reservation.
Interview Summary
Use circuit switching when resources are dedicated and continuous service is required. Use packet switching when many users must share links efficiently and resilience to routing changes is important. The principal trade-off is guaranteed, dedicated capacity versus flexible, statistically shared capacity.
8
How do bandwidth, throughput, and latency differ in computer networks?
KnownRevise
Bandwidth is the maximum amount of data a link can carry per unit of time, throughput is the amount of data actually delivered per unit of time, and latency is the delay experienced when data travels between two points. These metrics describe capacity, realized performance, and responsiveness respectively.
Read full answerHide full answer
Applies tocomputer networks (TCP/IP, Ethernet, and general Internet systems)
Key Definitions
Metric
Meaning
Typical unit
Main question
Bandwidth
Available or theoretical capacity of a link
bits per second (bps, Mbps, Gbps)
How much data could the link carry?
Throughput
Actual rate of useful data transferred
bits per second
How much data was delivered successfully?
Latency
Delay between sending and receiving data
milliseconds (ms)
How long does the data take to arrive?
Bandwidth describes the maximum capability of a network path. For example, a 1 Gbps Ethernet link has a nominal bandwidth of 1 Gbps under ideal conditions.
Throughput accounts for protocol overhead, contention, retransmissions, acknowledgments, and other impairments. It may approach bandwidth on an unloaded, low-loss path but is usually lower.
Latency is commonly reported as round-trip time (RTT), which is the time for a request and its response to complete. One-way latency and RTT are different measurements.
How Latency Is Formed
End-to-end latency consists of several components:
Propagation delay: Time for a signal to travel through the physical medium.
Transmission delay: Time required to place all packet bits onto the link.
Processing delay: Time spent by routers, switches, NICs, and applications handling the data.
Queueing delay: Time spent waiting in buffers, such as a router output queue or TCP socket receive buffer.
The transmission-delay formula is:
[ text{Transmission delay}=frac{text{packet size in bits}}{text{link bandwidth}} ]
Propagation delay depends on distance and the signal’s propagation speed:
If the propagation delay is 20 ms, processing takes 0.5 ms, and queueing takes 2 ms, the one-way latency is:
[ 20+0.12+0.5+2=22.62text{ ms} ]
Assuming a symmetric return path, the approximate RTT is:
[ 2 times 22.62=45.24text{ ms} ]
The link’s bandwidth remains 100 Mbps, but this calculation determines how quickly an individual packet reaches its destination. Latency and bandwidth are therefore independent: a high-bandwidth connection can still have high latency.
Bandwidth-Delay Relationship
The bandwidth-delay product (BDP) estimates how many bits can be “in flight” on a path before the sender receives feedback:
The BDP helps explain TCP window sizing. A receive window that is too small limits throughput on high-latency paths, even when the link has abundant bandwidth.
Real-World Trade-Offs
More bandwidth reduces transmission delay for a given packet size, but it cannot remove long propagation delay.
Lower latency improves responsiveness and reduces the time required for TCP acknowledgments and congestion feedback.
Higher throughput improves download and data-transfer speed but does not necessarily improve request-response responsiveness.
Jitter is variation in latency. Real-time applications such as voice and video are affected by both latency and jitter.
In Linux and Internet systems, measured throughput is often affected by CPU scheduling, buffer sizes, packet loss, TCP congestion control, and contention on shared links.
ping commonly measures RTT, while curl can report transfer speed. ss displays TCP connection and queue information, and tcpdump can reveal packet timing and retransmissions.
A high-capacity link may therefore have poor interactive performance if propagation or queueing delays are high, while a lower-bandwidth link with low latency can feel more responsive.
9
How are transmission delay and propagation delay calculated?
KnownRevise
Transmission delay is the time required to push all bits of a packet onto a link, while propagation delay is the time required for a signal to travel the physical distance of that link.
Read full answerHide full answer
Applies tocomputer networks (general TCP/IP and OSI concepts)
Core Formulas
Delay
Formula
Main inputs
Transmission delay
(d_{text{transmission}} = frac{L}{R})
Packet length (L) in bits and link rate ® in bits per second
Propagation delay
(d_{text{propagation}} = frac{D}{S})
Distance (D) and signal propagation speed (S)
Packet length (L): Convert bytes to bits using (L = text{bytes} times 8).
Link rate ®: For 100 Mbps, use (100 times 10^6) bits per second.
Distance (D): Express both distance and speed in compatible units.
Propagation speed (S): A common approximation is (2 times 10^8) meters per second for typical network media.
Transmission and propagation delays occur simultaneously for different bits of the same packet. Therefore, the total time before the entire packet reaches the next hop is:
In the continuous-stream model, the first bit reaches the destination after approximately 500 μs. The final bit reaches it after approximately 620 μs, because the complete packet serialization interval is 120 μs.
Common Distinctions
Transmission delay depends on packet size and link rate: A larger packet or slower link increases it.
Propagation delay depends on distance and propagation speed: Increasing link length increases it, but increasing link bandwidth does not.
Transmission delay is calculated per hop: Use the capacity of the outgoing link for that hop.
Propagation delay accumulates across a path: Each physical link contributes its own distance-based delay.
Bandwidth and propagation speed are different: Bandwidth measures how many bits can be placed on a link per second; propagation speed measures how quickly the signal physically moves.
End-to-end delay also includes processing and queuing: Routers may need time to process headers or wait in output queues. Real Internet paths can therefore exceed the simple two-term calculation.
Interview Pitfalls and Practical Checks
Use bits, not bytes, with a link rate expressed in bits per second.
1 Mbps normally means (10^6) bits per second, not (2^{20}) bits per second.
Do not confuse round-trip time with one-way propagation delay. ping reports an RTT, which includes propagation in both directions plus processing, queuing, and response transmission.
traceroute can help identify per-hop paths, while tcpdump can provide packet timestamps. Neither directly isolates transmission delay from every other delay component.
In textbook models, packets are often assumed to arrive without loss or queueing. Real TCP/IP stacks may experience retransmissions, congestion, variable link rates, and queuing, so measured delays can differ substantially from the calculated values.
10
How do unicast, multicast, broadcast, and anycast differ?
KnownRevise
Unicast, multicast, broadcast, and anycast describe different destination-delivery patterns in an IP network. Unicast targets one receiver, multicast targets a group, broadcast targets every host in a limited domain, and anycast routes traffic to one available instance of a replicated service.
Read full answerHide full answer
Applies toIPv4 and IPv6 networking, including Ethernet, IP routing, DNS, and application protocols
Core Definitions
Unicast: A sender communicates with one specific receiver using that receiver’s address. It is the normal form of communication for TCP connections, HTTPS requests, and SSH sessions.
Multicast: A sender transmits to a group of receivers identified by a multicast group address. Membership and group reachability are managed through protocols such as IGMP for IPv4 and MLD for IPv6.
Broadcast: A sender transmits to every host in a particular broadcast domain. Broadcast is normally confined to a local link and is not forwarded by routers.
Anycast: Multiple locations advertise the same service address, and routing directs a request to one of those locations. The selected location is typically the one considered best by the routing system, often the nearest according to routing policy.
Comparison
Delivery type
Number of intended receivers
Address model
Typical scope
Example
Unicast
One
A host’s unicast address
End-to-end or routed path
Client connecting to a web server
Multicast
A subscribed group
Multicast group address
Configured multicast domains
Live video distribution
Broadcast
All hosts in a domain
Broadcast address
Usually one LAN or VLAN
ARP request in IPv4
Anycast
One selected service instance
Shared service prefix
Globally routable service
Query to a public DNS resolver
Multicast and broadcast are destination-addressing mechanisms. Anycast is better understood as a routing and service-deployment technique: the packet still contains one destination address, but multiple sites originate routing advertisements for that address.
How Routing Handles Them
Unicast routing: Routers maintain routes to destination prefixes and forward each packet toward the selected next hop.
Multicast routing: The sender joins a multicast group, and multicast-capable routers maintain distribution trees or forwarding state for that group.
Broadcast forwarding: Routers generally do not forward Ethernet broadcasts beyond the originating broadcast domain. VLANs and routers commonly form broadcast-domain boundaries.
Anycast selection: Multiple providers or sites announce the same IP prefix through BGP or another routing protocol. Each router chooses a destination according to its routing table and policies.
For IPv4, multicast addresses use the 224.0.0.0/4 range. IPv6 multicast addresses use ff00::/8. IPv4 also has limited and subnet-directed broadcast addresses; subnet-directed broadcast support is often disabled in modern routed networks for security reasons.
Concrete Example
Suppose a company operates the same service at three data centers:
A client using unicast is sent to one explicitly chosen server address.
A service using anycast advertises one shared address from all three data centers. The client’s DNS response contains that address, and BGP routes the request to one data center.
A live event uses multicast so that every authorized subscriber receives the stream.
A device using broadcast sends a message that is processed by every host on its local VLAN, such as an IPv4 ARP request.
Anycast is widely used by public DNS resolvers and content-delivery networks. It improves availability and can exploit normal routing decisions, but it does not guarantee that the geographically closest server will be selected because BGP policy, peering, and load can affect the route.
Trade-offs and Practical Considerations
Unicast: Simple and universally supported, but serving many recipients individually can create unnecessary traffic and load.
Multicast: Efficient for one-to-many delivery, but requires group membership, multicast-aware routing, and careful handling of access control.
Broadcast: Easy for local discovery, but can cause unnecessary processing and can be abused for amplification attacks.
Anycast: Provides simple service addressing and rapid failover without client-side load-balancing logic, but traffic distribution depends on routing policy and may be uneven.
In the textbook model, these are clean delivery categories. In real Linux and cloud networks, reachability may be shaped by VLANs, subnets, firewalls, NAT, IGMP snooping, and BGP policies. In particular, multicast and broadcast behavior is often restricted at network boundaries, while anycast depends heavily on how the service’s prefix is advertised.
11
How does a MAC address differ from an IP address?
KnownRevise
A MAC address identifies a network interface on a local link, while an IP address identifies a host’s interface within an IP network and supports communication across interconnected networks. MAC addresses operate primarily at the data link layer, whereas IP addresses operate at the network layer.
Read full answerHide full answer
Applies toall versions of Ethernet, IPv4, and IPv6
Key Differences
Property
MAC address
IP address
OSI layer
Data link layer (Layer 2)
Network layer (Layer 3)
Typical size
48 bits
32 bits for IPv4; 128 bits for IPv6
Representation
00:1A:2B:3C:4D:5E
192.168.1.25 or 2001:db8::25
Primary purpose
Identifies interfaces on a local link
Identifies interfaces across IP networks
Addressing structure
Usually based on an IEEE-assigned manufacturer identifier
Hierarchical, based on network and subnet prefixes
Scope
Local link
Potentially global, depending on routing and configuration
Resolution mechanism
Learned directly from frames and address tables
IPv4 uses ARP; IPv6 uses Neighbor Discovery
Typical forwarding device
Ethernet switch
IP router
A MAC address is commonly displayed in six groups of two hexadecimal digits. The first 24 bits often identify the manufacturer through an Organizationally Unique Identifier (OUI), although locally administered addresses and newer randomized approaches are also used.
IPv4 addresses are divided into network and host portions by a subnet mask or CIDR prefix. IPv6 addresses similarly use prefixes, but provide a much larger address space and commonly construct interface identifiers using privacy extensions rather than a traditional Ethernet hardware address.
How It Works
On a local Ethernet segment, switches forward frames according to destination MAC addresses. The switch maintains a MAC address table that maps MAC addresses to switch ports, reducing unnecessary frame delivery.
IP addresses are hierarchical. Routers use the destination IP address and routing table to select the next hop toward the destination network. A router removes the incoming Layer 2 frame and creates a new frame for the outgoing link.
Therefore, a packet’s IP addresses generally remain unchanged while it crosses routers, although NAT may modify IPv4 addresses. Its Layer 2 frame, including the source and destination MAC addresses, is normally rebuilt at every routed hop.
Concrete Example
Suppose a laptop has:
MAC address: 00:1A:2B:3C:4D:5E
IPv4 address: 192.168.1.25
Default gateway: 192.168.1.1
When the laptop accesses 8.8.8.8:
It determines that 8.8.8.8 is outside its local subnet.
It sends the IP packet to the gateway’s IP address, 192.168.1.1.
The Ethernet frame is addressed to the gateway’s MAC address, not to 8.8.8.8.
The router forwards the packet using the destination IP address 8.8.8.8.
MAC addresses matter only on each local link. The laptop’s MAC address is not normally carried as the destination through the Internet; every router replaces the Layer 2 addressing for the next link.
Assignment and Identifiability
MAC assignment: Traditionally associated with an Ethernet interface, but modern systems can change or randomize it. Operating systems such as Windows, macOS, and Linux support “private” or randomized Wi-Fi MAC addresses.
IP assignment: May be statically configured or assigned through DHCP for IPv4; IPv6 commonly uses SLAAC, while DHCPv6 is optional and may provide addresses or other configuration.
One-to-many relationships: One interface can possess multiple IP addresses, and NAT allows many private hosts to share one public IPv4 address.
Security: Neither type is a strong identity credential. MAC addresses can be spoofed, and IP addresses can also be spoofed, although ingress filtering and other controls can limit such attacks.
Common Interview Pitfalls
Do not say that MAC addresses are globally unique in an absolute sense; they are locally administered in some cases and can be changed or spoofed.
Do not say that MAC addresses identify a device. They identify a network interface.
Do not claim that an IP address always identifies one physical computer; it identifies an interface or endpoint within a routing domain.
IPv4 supports broadcast, while IPv6 does not. A broadcast MAC address such as ff:ff:ff:ff:ff:ff is also local to the Ethernet link and is unrelated to the IPv4 limited broadcast address 255.255.255.255.
12
What is data link layer framing in computer networks?
KnownRevise
Framing is the data link layer process of encapsulating a network-layer packet into a link-specific unit called a frame. The receiver identifies the frame boundaries, validates it, removes the link-layer fields, and passes the enclosed packet to the network layer.
Read full answerHide full answer
Applies toall versions of computer networking (OSI data link layer, Ethernet, IEEE 802.11, and PPP)
How Framing Works
The data link layer adds fields required for delivery over a particular link technology. A simplified frame commonly contains:
Header: destination and source link-layer addresses, frame type, and control information.
Payload: the packet received from the network layer.
Trailer: error-detection information, often a Frame Check Sequence (FCS).
The transmitter marks where a frame begins and ends, while the receiver uses those boundaries to extract complete frames from the incoming bit stream. Framing is therefore distinct from encapsulation: framing identifies and structures the link-layer unit, while encapsulation places a higher-layer message inside it.
Example: Sending an IP Packet over Ethernet
Suppose a host sends a 100-byte IPv4 packet over standard Ethernet:
Field
Size
Ethernet header
14 bytes
IP packet
100 bytes
Ethernet FCS
4 bytes
Total frame
118 bytes
The receiver removes the 14-byte Ethernet header and 4-byte FCS, then passes the 100-byte IP packet upward. Ethernet frames must be at least 64 bytes from the destination address through the FCS, so a frame shorter than that limit is padded. The 8-byte preamble and Start Frame Delimiter precede the frame on the medium but are not part of the 64-byte minimum frame size.
Error Detection and Handling
FCS: Ethernet uses CRC-32 to detect transmission errors.
Validation: a receiver or switch calculates the CRC and discards a corrupted frame.
Upper-layer recovery: TCP uses sequence numbers, acknowledgements, and its own checksum to recover from missing or damaged data.
Wireless acknowledgements: IEEE 802.11 uses link-layer acknowledgements and automatic retries for frames requiring acknowledgement because radio links are especially susceptible to noise and interference.
Thus, error detection at the data link layer does not imply guaranteed delivery. A damaged Ethernet frame is usually discarded, and recovery may occur through retransmission by TCP or another higher-layer protocol.
Textbook Model Versus Real Systems
The classic OSI data link layer also includes flow control and error control. Textbook examples often describe reliable link protocols that acknowledge frames, retransmit missing frames, and regulate the sender’s rate.
Modern LAN systems behave differently:
Ethernet: switched full-duplex Ethernet provides frame delivery with FCS checking but generally relies on upper layers for end-to-end recovery.
Wi-Fi: IEEE 802.11 includes MAC acknowledgements and automatic ARQ retries, with configurable retry limits and policies.
Point-to-point links: protocols such as PPP provide framing, link negotiation, optional authentication, and error detection.
Virtual links: tunnels and overlay networks may add additional framing around packets before transmission.
Common Pitfalls and Trade-offs
Frame versus packet: a frame is a data link layer unit; a packet is usually a network-layer unit.
Frame size versus MTU: the link imposes a maximum frame payload size, commonly 1500 bytes for standard Ethernet. Larger network-layer packets must be fragmented or rejected according to the protocol.
Link address versus IP address: Ethernet MAC addresses identify interfaces on the local link, while IP addresses support end-to-end routing across networks.
FCS versus checksum: an FCS protects one link transmission; a transport checksum can provide end-to-end error detection over a connection.
Boundary detection: not every technology uses a simple length field. Ethernet relies on physical-layer preamble and delimiter signals, whereas protocols such as PPP use explicit frame delimiters.
13
How do parity, checksum, and CRC detect transmission errors?
KnownRevise
Parity, checksum, and cyclic redundancy check (CRC) detect accidental transmission errors by adding redundant information to the original data. Parity is simple and inexpensive, checksum provides stronger protection with little overhead, while CRC provides the strongest and most widely used protection for network frames.
Read full answerHide full answer
Applies tocomputer networks (Ethernet, IPv4, IPv6, and TCP/UDP)
Core Idea
The sender calculates a value from the data and transmits it with the data. The receiver calculates the same value and compares the results.
Error detected: The calculated and received values differ.
Error undetected: The values match even though the data was corrupted.
Error correction: These methods normally detect errors; they do not automatically recover the original data.
Transmission errors include bit flips caused by noise, interference, attenuation, or faulty hardware.
How Each Method Works
Method
Redundant information
Typical use
Main limitation
Parity
One or more parity bits
Simple memory and serial links
Detects only some error patterns
Checksum
Sum or one’s-complement sum
IP, TCP, and UDP headers
Some multi-bit errors can cancel
CRC
Remainder from polynomial division
Ethernet and most data-link protocols
Detects errors but does not correct them
Parity
Even parity adds one bit so that the total number of 1 bits is even. Odd parity does the opposite.
For example, ASCII A is 01000001, which contains two 1 bits:
Even-parity bit: 0
Transmitted value: 010000010
The receiver counts the 1 bits and reports an error if the result is odd. Parity detects any odd number of flipped bits, but an even number of errors can leave the parity unchanged. Two-dimensional parity can improve detection, but it requires additional parity bits.
Checksum
A checksum groups data into fixed-size units, adds them using selected arithmetic, and transmits the resulting value. The receiver repeats the calculation and includes the received checksum in the comparison.
The Internet checksum used by IPv4, TCP, and UDP uses 16-bit one’s-complement addition:
Interpret data as 16-bit words.
Add the words, carrying overflow back into the sum.
Complement the final sum to obtain the checksum.
At the receiver, include the checksum in the sum; a correct result produces all 1 bits.
For two words 0x1234 and 0x5678:
Sum: 0x68AC
Checksum: ~0x68AC = 0x9753
Verification sum: 0x68AC + 0x9753 = 0xFFFF
Checksums are inexpensive and effective for many random errors, but carefully selected errors can cancel each other. TCP and UDP also include a pseudo-header containing addressing and protocol information.
Cyclic Redundancy Check
CRC treats a frame as a polynomial whose bits are coefficients. The sender:
Appends r zero bits to the data polynomial.
Divides it by a generator polynomial using modulo-2 division, equivalent to XOR without carries.
Appends the remainder as the frame check sequence (FCS).
The receiver divides the complete codeword by the same generator.
A correct frame has remainder zero; a nonzero remainder indicates corruption. With an r-bit CRC, all burst errors of length at most r bits are detected. With a generator containing x + 1, all odd-number bit errors are also detected.
Ethernet uses CRC-32 and adds a 4-byte FCS to each frame. The receiver checks and removes the FCS before passing the payload upward.
Practical Usage and Trade-offs
Parity is useful where extremely low complexity matters, but it is rarely sufficient for noisy networks.
Checksum is common in transport and network-layer protocols because it requires little computation.
CRC is preferred at the data-link layer because hardware can calculate it at line rate and it detects nearly all practical frame errors.
End-to-end checking: TCP and UDP checksums verify data across the complete path, whereas Ethernet CRC checks each link independently.
Security boundary: Parity, checksum, and CRC protect against accidental corruption, not malicious modification. Cryptographic MACs or authenticated encryption are required for security.
For example, tcpdump can capture Ethernet frames for inspection, while ss and application logs can help diagnose transport-layer checksum failures. In production systems, CRC or cryptographic integrity should be selected according to the required error probability and threat model.
14
How does a Hamming code detect and correct transmission errors?
KnownRevise
A Hamming code adds redundant parity bits to data so that a receiver can identify and correct an isolated single-bit transmission error. A basic Hamming code corrects one-bit errors, while the SECDED extension can also detect double-bit errors.
Read full answerHide full answer
Applies tocomputer networks (general Hamming coding and SECDED ECC)
How It Works
For a canonical Hamming code with (m) data bits and ® parity bits, the codeword length is (m+r=2^r-1), so:
[ 2^r ge m+r+1 ]
This provides a distinct ®-bit syndrome for every possible single-bit error position.
Data bits: In the canonical, unshortened code, they occupy positions that are not powers of two.
Parity bits: They occupy positions (1,2,4,8,ldots).
Parity check: The parity bit at position (2^k) covers every codeword position whose binary index contains bit (k).
Syndrome: At the receiver, the parity checks are recomputed. A failed check contributes a 1 to the corresponding syndrome bit.
Correction: If exactly one bit is wrong, the nonzero syndrome equals that bit’s position, so the receiver flips it.
For even parity, each covered set must contain an even number of 1 bits after encoding. Syndrome 0 means that all parity checks pass, although a multi-bit error can occasionally be undetected.
Hamming(7,4) Worked Example
Hamming(7,4) contains four data bits and three parity bits:
Position
1
2
3
4
5
6
7
Content
(p_1)
(p_2)
(d_1)
(p_4)
(d_2)
(d_3)
(d_4)
With even parity:
(p_1) covers positions 1, 3, 5, and 7.
(p_2) covers positions 2, 3, 6, and 7.
(p_4) covers positions 4, 5, 6, and 7.
For data bits 1011:
(p_1=0), because its covered set contains two 1 bits.
(p_2=1), because its covered set contains three 1 bits.
(p_4=0), because its covered set contains two 1 bits.
The resulting codeword is 0110011. If position 5 flips, the receiver receives 0110111. The (p_1) and (p_4) checks fail, while the (p_2) check succeeds. The syndrome is therefore (c_4c_2c_1=101_2=5), identifying position 5. Flipping that bit restores 0110011 and recovers the original data 1011.
Detection and Correction Limits
Variant
Minimum distance
Correction capability
Practical detection behavior
Basic Hamming(7,4)
3
Corrects any single-bit error
A double-bit error can yield a nonzero syndrome and be miscorrected
Extended Hamming, SECDED
4
Corrects any single-bit error
Detects double-bit errors using an additional overall parity bit
SECDED means single-error correction, double-error detection. It adds one overall parity bit over the complete Hamming codeword. The basic syndrome decoder and the SECDED decoder therefore have different behavior: the former assumes at most one error, while the latter can distinguish a single-bit error from a double-bit error.
Practical Use and Best Practices
Use basic Hamming codes when low overhead and single-bit correction are sufficient.
Use SECDED when memory or storage must correct one-bit errors and reliably flag double-bit errors, as in ECC memory.
Add interleaving when burst errors are likely; ordinary Hamming codes are primarily intended for isolated bit errors.
In network protocols, CRC combined with acknowledgements and retransmission is generally more practical because it efficiently detects multi-bit and burst errors.
Do not treat every nonzero basic-Hamming syndrome as proof of a single-bit error unless the surrounding system guarantees that no additional errors occurred.
15
How do stop-and-wait and sliding window protocols control data flow?
KnownRevise
Flow control prevents a sender from transmitting faster than the receiver can process data. Stop-and-wait permits only one unacknowledged frame, while a sliding window allows a bounded number of frames to remain in transit.
Read full answerHide full answer
Applies tocomputer networks (OSI data link and transport layers; TCP/IP and general networking concepts)
How Flow Control Works
Flow control is different from error control:
Flow control protects the receiver’s buffer and prevents data loss caused by excessive incoming data.
Error control uses sequence numbers, checksums, acknowledgements, and timers to detect loss, corruption, or duplication. Lost or corrupted data is retransmitted, while duplicate frames are discarded.
A receiver may advertise how much additional data it can accept. The sender must not exceed that limit. If no receiver-side capacity information exists, a protocol may use a fixed window size, but that window must still fit the receiver’s available buffering.
Stop-and-Wait Protocol
In stop-and-wait ARQ, the sender follows these steps:
Transmit one numbered frame.
Stop sending and wait for its acknowledgement.
If the acknowledgement arrives before a timeout, send the next frame.
If the timeout expires, retransmit the frame.
Use sequence numbers to distinguish a retransmission from a new frame.
If the original frame was delayed and the receiver already processed it, the receiver can discard the duplicate and acknowledge the same sequence number again.
A timeout must be chosen carefully:
If it expires too early, unnecessary retransmissions occur.
If it expires too late, the sender remains idle after a lost acknowledgement.
Duplicate frames still consume bandwidth, even though they do not corrupt the delivered data stream.
Sliding Window Protocol
With a sliding window, the sender may have up to W frames outstanding. Sequence numbers identify frames, acknowledgements advance the window, and new frames can be sent as earlier ones are acknowledged.
Two important forms are:
Go-Back-N: On an error or timeout, retransmit the missing frame and all subsequent frames.
Selective Repeat: Retransmit only missing or damaged frames.
The receiver’s window limits the number of frames it may accept out of order. This prevents duplicate or excessively reordered data from occupying its buffer.
TCP uses a sliding-window design with cumulative acknowledgements, retransmission timers, and a receiver-advertised window. TCP’s congestion control is separate: it limits in-flight data according to network conditions, while the receiver window limits it according to receiver capacity.
Worked Example
Assume a 100 Mbit/s link carries 1500-byte frames, one-way propagation delay is 10 ms, and acknowledgement transmission time is negligible.
ceil(250,000 / 1,500) = 167 frames represent that BDP.
For continuous transmission, however, the first acknowledgement cannot return until Tframe + 2Tpropagation = 20.12 ms after transmission begins. Transmitting 167 frames takes 167 × 0.12 = 20.04 ms, leaving an 0.08 ms idle interval. Therefore, the exact whole-frame window is:
W = ceil(20.12 / 0.12) = 168 frames.
This 168-frame result assumes an error-free link and ignores protocol overhead.
Stop-and-Wait vs Sliding Window
Property
Stop-and-Wait
Sliding Window
Unacknowledged frames
At most 1
Up to W
Link utilization
Low on long-delay links
High when W covers the bandwidth-delay product
Buffer requirements
Minimal
Receiver needs buffering for permitted out-of-order frames
Retransmission
Retransmit one frame
Retransmit one or several frames
Complexity
Simple
More sequence-number and buffering logic
Main use
Simple or low-rate links
High-throughput transports such as TCP
Practical Considerations and Pitfalls
A small window can cause the sender to wait even when the network has available capacity.
A window larger than the receiver’s buffer can overflow the receiver unless flow-control advertisements are honored.
The sequence-number space must be large enough to avoid confusing old retransmissions with new frames.
Timeout values should be based on measured round-trip times rather than fixed guesses.
Stop-and-wait is especially inefficient on satellite or geographically distant links because each frame requires a full round trip.
TCP implements sliding-window flow control, while UDP provides neither acknowledgements nor built-in flow control.
16
How do Go-Back-N and Selective Repeat ARQ differ?
KnownRevise
Go-Back-N (GBN) retransmits an entire unacknowledged sequence of frames when a timeout occurs, whereas Selective Repeat (SR) retransmits only the missing or damaged frame. GBN is simpler but less efficient on lossy links; SR provides better throughput at the cost of more receiver buffering and complexity.
Read full answerHide full answer
Applies tocomputer networks (data link layer, sliding-window ARQ protocols)
Core Differences
Property
Go-Back-N
Selective Repeat
Acknowledgment model
Usually cumulative ACK
Individual or selective ACK
Timeout response
Retransmit the timed-out frame and every later frame
Retransmit only the timed-out frame
Receiver buffer
Does not accept out-of-order frames; they are discarded
Buffers out-of-order frames until the missing frame arrives
Sender window size
At most (2^m-1)
At most (2^{m-1})
Efficiency on loss
Lower because multiple valid frames may be resent
Higher because only the lost frame is resent
Complexity
Lower
Higher due to timers, buffering and selective acknowledgments
Here, (m) is the number of bits used for sequence numbers.
How Go-Back-N Works
The sender maintains a window of frames and numbers them modulo (2^m). A receiver normally discards frames that arrive outside its expected sequence number.
The sender transmits frames continuously within its window.
The receiver cumulatively acknowledges the highest correctly received frame.
If frame (k) times out, the sender retransmits (k) and every subsequent frame in the window.
The receiver discards duplicates of frames it already received.
For example, suppose the sender transmits frames 1, 2, 3, 4, but frame 2 is lost. Frames 3 and 4 may reach the receiver, but the receiver expects frame 2 and discards them. If frame 2 times out, GBN retransmits 2, 3, 4.
This design prevents unbounded out-of-order buffering, but retransmissions can waste bandwidth when the lost frame is followed by frames that arrived successfully.
How Selective Repeat Works
The receiver can accept and buffer frames that arrive out of order. Each frame effectively needs selective acknowledgment, and the sender maintains a timer for outstanding frames.
For the same example, if frame 2 is lost:
Frames 3 and 4 are stored in the receiver’s buffer.
Frame 2 is retransmitted after its timeout.
The receiver accepts frame 2 and then delivers the buffered frames 3 and 4 in order.
SR avoids retransmitting successfully received frames. However, it requires enough receiver and sender buffering to distinguish old duplicates from new frames. The smaller maximum window of (2^{m-1}) prevents sequence-number ambiguity.
Worked Window Example
With 3-bit sequence numbers, the sequence space is:
[ 2^3 = 8 ]
Therefore:
Go-Back-N: maximum sender window (= 2^3-1 = 7)
Selective Repeat: maximum sender window (= 2^{3-1} = 4)
With 4-bit sequence numbers:
Go-Back-N: maximum window (= 2^4-1 = 15)
Selective Repeat: maximum window (= 2^{4-1} = 8)
The smaller SR window is necessary because the sender and receiver must avoid confusing a retransmitted frame with a new frame using a reused sequence number.
GBN limitation: one loss can cause several unnecessary retransmissions, reducing throughput.
SR advantage: retransmits only erroneous frames, making it more suitable for high-delay or lossy links.
SR limitation: requires per-frame timers or equivalent timer management, selective acknowledgments, and larger buffers.
These are primarily textbook data-link-layer models. Real TCP implementations use cumulative acknowledgments but do not implement pure GBN or pure SR. Modern TCP stacks generally use fast retransmit, duplicate acknowledgments, and congestion-control algorithms such as CUBIC to retransmit missing data while avoiding the inefficiency of retransmitting every subsequent segment.
17
What is CSMA/CD, and why does modern Ethernet avoid it?
KnownRevise
CSMA/CD is the historical Carrier Sense Multiple Access with Collision Detection access method used by shared Ethernet. Modern Ethernet generally avoids it by using switched, point-to-point full-duplex links, which have no shared medium or collision domain and allow a station to transmit and receive simultaneously.
Read full answerHide full answer
Applies toIEEE 802.3 Ethernet (legacy shared half-duplex through current switched full-duplex operation)
How CSMA/CD Works
CSMA/CD operates at the Ethernet MAC sublayer, corresponding to the data link layer in the OSI model. A station follows this process:
Carrier Sense: Listen to the shared medium to determine whether it is busy.
Multiple Access: All stations connected to the same shared medium may attempt transmission.
Collision Detection: Continue monitoring the medium while transmitting and compare the transmitted and received signals. A collision occurs when signals from different stations overlap.
Jam Signal: Transmit a jam signal so the other stations also recognize that a collision occurred.
Binary Exponential Backoff: After repeated collisions, double the contention window up to its defined maximum and select a random number of slot times to wait.
Retransmission: Sense the medium again and retransmit when it is available.
Carrier sensing alone cannot prevent every collision because another station’s signal may not yet have reached the transmitting station. For this reason, Ethernet requires a frame to remain in transit long enough to detect a collision. This requirement contributed to the 64-byte minimum Ethernet frame size, excluding the preamble and start-frame delimiter.
Why It Is No Longer Needed
Early Ethernet used a shared medium, including coaxial cable and hubs connected through repeaters. Every station shared the same bandwidth and collision domain.
Shared half-duplex Ethernet
Switched full-duplex Ethernet
Stations share one medium
Each station has a point-to-point switch link
Only one station can transmit successfully at a time
A station can transmit and receive simultaneously
Collisions are possible
Collisions do not occur
CSMA/CD and backoff are used
CSMA/CD is disabled
Performance degrades as more stations contend
No contention occurs on an individual full-duplex link
A switch learns source MAC addresses and uses them to forward known-unicast frames to the destination port. Unknown unicast and broadcast frames are flooded within the relevant VLAN. Full duplex eliminates the shared signal on which CSMA/CD depends, so no collision detection or backoff is required.
Concrete Example
Consider four computers connected to a 10 Mbps hub. If two computers transmit at nearly the same instant, their electrical signals collide. Both stations detect the collision, stop transmitting, select random backoff intervals, and try again. The hub repeats incoming signals to the other ports, so all four computers share one 10 Mbps collision domain.
If the same computers connect to a full-duplex switch, each computer-to-switch link is independent. Computer A can upload while Computer B downloads, and neither link requires collision detection. The switch’s uplink or internal fabric can still become a bandwidth bottleneck, but that is not an Ethernet collision-domain problem.
Modern Standards and Practical Impact
IEEE 802.3 still defines half-duplex operation, including CSMA/CD, for legacy and shared-media compatibility. Switched full-duplex Ethernet is normally used today; however, a half-duplex link still uses CSMA/CD.
A duplex mismatch, where one endpoint operates full duplex and the other operates half duplex, can cause late collisions, frame-check-sequence errors, retransmissions, and severe throughput loss. Administrators should verify the negotiated mode with ethtool and inspect interface statistics with ip -s link.
18
What is CSMA/CA in Wi-Fi and why is it used?
KnownRevise
Carrier Sense Multiple Access with Collision Avoidance (CSMA/CA) is the IEEE 802.11 Medium Access Control mechanism used to coordinate transmissions among Wi-Fi stations. It reduces the probability of collisions by sensing the channel, waiting for a random backoff period, and optionally reserving the medium with RTS/CTS frames.
Read full answerHide full answer
Applies tocomputer networks (all IEEE 802.11 wireless LAN versions)
How CSMA/CA Works
The basic IEEE 802.11 Distributed Coordination Function (DCF) follows this sequence:
A station with a frame to send senses the medium.
If the medium is busy, it waits until it remains idle for the Distributed Inter-Frame Space (DIFS).
It selects a random backoff counter within the Contention Window (CW).
The counter decreases by one for each idle slot and freezes while the medium is busy. It resumes decrementing when the medium becomes idle again.
When the counter reaches zero, the station transmits.
The receiver sends an ACK after a Short Inter-Frame Space (SIFS). An ACK confirms successful reception; otherwise, the sender retries according to its configured retry limits.
A simplified timing example is:
Station A chooses a backoff of 5 slots.
Station B chooses a backoff of 2 slots.
If the channel is initially idle, B transmits first.
After B’s frame and ACK, A continues its remaining backoff and then transmits.
The random selection prevents stations from repeatedly transmitting at exactly the same time.
Why Wireless Uses Collision Avoidance
Traditional Ethernet commonly uses CSMA with Collision Detection (CSMA/CD). A wired station can transmit while simultaneously listening for a collision because its own signal is much stronger than other stations’ signals.
That approach is impractical in most wireless networks:
Wired Ethernet
Wi-Fi
A station can often detect a collision while transmitting
A station usually cannot reliably detect a collision while transmitting
Collision detection is feasible
Collision avoidance and acknowledgment are used instead
Full-duplex switched Ethernet does not require CSMA/CD
A Wi-Fi radio’s transmitted signal can be millions of times stronger than an incoming signal, making simultaneous collision detection difficult. Wi-Fi therefore attempts to reduce collisions and uses ACK-based recovery when they still occur.
RTS, CTS, and the Hidden Node Problem
In a hidden-node scenario, Station A and Station C cannot hear each other, but both can hear Station B. If A and C transmit simultaneously, their frames may collide at B.
CSMA/CA addresses this using optional Request to Send/Clear to Send (RTS/CTS):
A sends an RTS frame.
B responds with a CTS frame.
Other stations hearing the CTS stop transmitting for the Network Allocation Vector (NAV) duration.
A sends the data frame, and B acknowledges it.
The reservation is not guaranteed to eliminate every collision, especially when two hidden transmitters begin simultaneously, but it substantially reduces the contention window in which a collision can occur.
Modern Wi-Fi may use RTS/CTS selectively, while basic access remains available for shorter frames or less congested situations.
Advantages and Limitations
Advantages: Simple distributed operation, no central coordinator, compatibility with dynamic wireless links, and reduced collision probability.
Limitations: Random backoff introduces delay, throughput can decline as contention increases, and hidden nodes remain challenging.
Real-system behavior: Practical Wi-Fi also uses acknowledgments, retries, rate adaptation, fragmentation, aggregation, and quality-of-service rules such as EDCA. These mechanisms complement rather than replace CSMA/CA.
Common Pitfalls
CSMA/CA does not guarantee collision-free transmission.
Carrier sensing alone cannot identify every hidden node.
The ACK is important: a transmitted frame is not necessarily successfully received.
SIFS and DIFS are different because ACK and control frames take priority over ordinary data contention.
19
How does ARP resolve IP addresses to MAC addresses?
KnownRevise
ARP (Address Resolution Protocol) is a link-layer protocol that maps an IPv4 address to a physical MAC address within the local broadcast domain. It lets a host determine the MAC address needed to place an Ethernet frame on the wire.
Read full answerHide full answer
Applies toIPv4 Ethernet networks (ARP as specified in RFC 826)
How ARP Works
The operating system checks its ARP cache, also called a neighbor table, for an IPv4-to-MAC mapping.
If a usable entry exists, the host uses the cached MAC address as the destination hardware address of the Ethernet frame.
If no usable entry exists, the host broadcasts an ARP request: “Who has 192.0.2.10? Tell me your MAC address.” The request uses the broadcast MAC address ff:ff:ff:ff:ff:ff.
The host owning the requested IPv4 address receives the request and normally returns a unicast ARP reply containing its MAC address.
The requester caches the reply and sends the original IP packet using the newly learned MAC address.
The ARP request/reply exchange itself is stateless, although hosts maintain local cache state. A responder can also learn the requester’s address-to-MAC mapping from the request.
If the final destination is on another subnet, the host does not attempt to resolve the remote host’s MAC address. After route lookup, it resolves the MAC address of its next-hop router, normally the default gateway.
ARP Cache and Management
Dynamic entries: Learned from ARP traffic and normally expire when they become stale or are removed according to the operating system’s neighbor-discovery policy. Exact lifetimes vary by OS and configuration; Linux derives them from parameters such as base_reachable_time and adds random jitter.
Static entries: Configured manually and do not use ordinary dynamic-entry aging. They may remain until explicitly removed or the OS resets its configuration, depending on the platform.
Linux tools: Use ip neigh show to display the neighbor table. The older arp -a command is provided by the deprecated net-tools package.
Windows tools: Use arp -a to display the cache, arp -s to add a static entry, and arp -d to delete an entry.
Neighboring systems: ARP is specific to IPv4. IPv6 uses the Neighbor Discovery Protocol, which resolves link-layer addresses for IPv6.
ARP Packet Structure
Field
Size
Description
Hardware Type
2 bytes
Link-layer technology; 1 denotes Ethernet
Protocol Type
2 bytes
Address protocol; 0x0800 denotes IPv4
Hardware Size
1 byte
Hardware-address length; 6 for Ethernet
Protocol Size
1 byte
Protocol-address length; 4 for IPv4
Operation
2 bytes
1 for request and 2 for reply
Sender MAC
6 bytes
Sender’s Ethernet address
Sender IP
4 bytes
Sender’s IPv4 address
Target MAC
6 bytes
Normally zero or ignored in a request
Target IP
4 bytes
IPv4 address being resolved
For Ethernet and IPv4, the ARP payload is 28 bytes. It is carried in an Ethernet frame with EtherType 0x0806; the frame may also contain Ethernet padding to meet the minimum frame size.
Real-World Behavior and Tools
ARP broadcast frames are not routed across routers, so every subnet performs its own address resolution. A router may deliberately provide proxy ARP, but that is a configured router behavior rather than normal ARP forwarding.
To trigger resolution on a local IPv4 network, run ping -c 1 192.168.1.1, using an address that actually exists on the local segment.
Capture ARP packets on Linux with sudo tcpdump -n -i eth0 arp.
ip neigh on Linux and arp -a on Windows display neighbor information. Commands such as ss and netstat show socket and transport-layer information rather than the ARP cache.
Security: ARP Spoofing
ARP has no built-in authentication, so an attacker can send forged or unsolicited ARP replies and associate a legitimate IP address with the attacker’s MAC address. This can redirect traffic through the attacker and enable a man-in-the-middle attack.
A gratuitous ARP is an ARP announcement or update that may be used for address-conflict detection or legitimate network updates. It is not inherently malicious, although attackers can abuse similar behavior for poisoning.
Dynamic ARP Inspection (DAI) on managed switches validates ARP bindings against trusted information, commonly learned through DHCP snooping.
Static ARP entries can protect a specific mapping, but they are operationally difficult to maintain at scale.
IPv6 Neighbor Discovery is the corresponding protocol for IPv6. Secure Neighbor Discovery (SEND) can add cryptographic protection, but adoption is limited compared with ordinary IPv6 Neighbor Discovery.
Managed networks may combine DAI, DHCP snooping, switch port controls, and monitoring, but the exact protections depend on the organization’s design and deployment.
20
How does a VLAN segment networks and why is it useful?
KnownRevise
A Virtual Local Area Network (VLAN) logically partitions an Ethernet network into separate broadcast domains. VLANs let devices on the same physical switching infrastructure use independent Layer 2 configurations for segmentation, traffic management, and improved security isolation.
Read full answerHide full answer
Applies tocomputer networks (IEEE 802.1Q and current Ethernet/IP switching)
Definition and Purpose
A physical LAN connects devices through shared switches and cabling. A VLAN creates multiple logical LANs over that same infrastructure, allowing one switch or network fabric to carry traffic for different departments, applications, or security zones.
Each VLAN has its own broadcast domain, so a broadcast frame sent in one VLAN is not flooded into other VLANs. This reduces unnecessary broadcast traffic and provides basic Layer 2 segmentation.
A VLAN is distinct from related concepts:
Concept
Meaning
VLAN
Logical separation of Layer 2 broadcast domains
IP subnet
Logical grouping identified by an IP prefix
VPN
Encrypted tunnel that connects remote networks or hosts
Physical LAN
Actual cabling, switches, and connected devices
A VLAN and an IP subnet often correspond one-to-one, but they are not inherently the same. Routing between VLANs still requires a Layer 3 device such as a router, Layer 3 switch, or firewall.
How VLANs Work
IEEE 802.1Q defines VLAN tagging for Ethernet frames. When forwarding an untagged frame from an access port onto a tagged trunk, a switch adds an 802.1Q tag identifying the VLAN. Frames belonging to a trunk’s native VLAN may remain untagged.
VLAN identifier: Uses 12 bits. Normal configurable VLAN IDs are 1–4094.
Access port: Carries traffic for one VLAN and normally presents untagged frames to the attached endpoint.
Trunk port: Carries traffic for multiple VLANs, commonly using IEEE 802.1Q tags.
PVID: The per-port VLAN identifier assigned to untagged frames arriving on that port.
Native VLAN: A trunk’s designated VLAN for untagged traffic; this operational term and its exact behavior can vary between implementations.
Broadcast domain: Ordinary broadcasts are flooded only within their VLAN. Communication between VLANs requires Layer 3 forwarding.
The switch maintains VLAN membership information and a forwarding table, commonly with separate MAC-address entries for each VLAN. It floods a broadcast only through ports belonging to that VLAN.
Practical Uses
VLANs are commonly used for:
Department separation: Finance, engineering, and guest devices receive separate logical networks.
Broadcast reduction: Large groups of endpoints are divided into smaller broadcast domains.
Server isolation: Administrative, database, and application-server traffic can occupy separate VLANs.
Voice and data separation: IP phones and user data may use different VLANs, simplifying QoS and troubleshooting.
Guest access: Visitors can be placed in a restricted VLAN without exposing internal business systems.
Project or application segmentation: Teams or applications that require different policies can be separated logically.
For example, a campus switch could create:
VLAN
Purpose
Example address
10
Student devices
192.168.10.0/24
20
Faculty devices
192.168.20.0/24
30
Servers
192.168.30.0/24
40
IP phones
192.168.40.0/24
99
Guest access
192.168.99.0/24
A student laptop in VLAN 10 cannot directly access a server in VLAN 30 at Layer 2. The traffic must be forwarded at Layer 3 by a routing device such as a router, Layer 3 switch, or firewall that applies an appropriate policy.
Textbook Model Versus Real Systems
The textbook model describes a switch forwarding frames according to a VLAN membership table. Real systems implement the same principle in several ways:
Managed switches provide VLAN configuration through management interfaces such as a command-line interface, web interface, controller, or cloud portal.
Linux bridges and Open vSwitch create software VLANs using kernel networking and virtual interfaces.
Virtualized networks use virtual switches and tags between virtual machines, hypervisors, and physical uplinks.
Cloud networks may expose VLAN-like constructs, but many modern services use virtual routing and switching or security groups instead.
Hardware features, supported VLAN counts, tagging behavior, and management models vary between vendors, but the fundamental broadcast-domain separation remains consistent for VLAN implementations.
Scalability: Large networks require adequate switch capacity, standardized naming, and careful documentation.
Routing overhead: Communication between VLANs requires Layer 3 forwarding and appropriate routing rules.
Not complete security: VLAN separation does not encrypt traffic or replace firewall rules, authentication, endpoint security, or access controls.
Configuration risk: Incorrect trunk, PVID, or port settings can create loops, connectivity failures, or VLAN-hopping opportunities.
Best practice is to use 802.1Q-aware trunks, remove unused ports from the default VLAN, keep management interfaces in a dedicated VLAN, restrict inter-VLAN traffic with a firewall, and monitor for configuration drift.
21
How does Spanning Tree Protocol maintain loop-free Ethernet switching?
KnownRevise
Spanning Tree Protocol (STP) is a Layer 2 control protocol that prevents switching loops by calculating a logical tree of active links across interconnected bridges or switches. It keeps redundant physical paths available for resilience while placing selected ports in a blocking state.
Read full answerHide full answer
Applies toIEEE 802.1D STP, with IEEE 802.1w RSTP and IEEE 802.1s MSTP extensions
Purpose and Placement
STP operates at the data link layer, where switches forward Ethernet frames using MAC addresses. Without STP, a redundant Layer 2 topology can create:
Broadcast storms: broadcast frames are continuously replicated around the network.
MAC-table instability: the same source MAC address is learned on different ports as frames loop through switches.
Frame duplication: copies of a frame reach the destination through multiple paths.
Network-wide congestion or failure.
STP is not an IP-routing protocol. It prevents loops within a Layer 2 switched domain; routed networks still require routing protocols such as OSPF or BGP.
How STP Works
A spanning tree is a graph-theoretic structure connecting all reachable bridges without cycles. STP discovers this structure by exchanging Bridge Protocol Data Units (BPDUs).
Bridge identification: Each bridge has a bridge identifier. It is compared when selecting the root and during tie-breaking.
Root bridge election: The bridge with the lowest bridge identifier becomes the root bridge for that STP instance.
Root-port selection: Every non-root bridge chooses one port, called its root port, that provides the best path toward the root bridge. Selection considers root-path cost and tie-breaking rules.
Designated-port selection: For each network segment, one bridge is selected as the designated bridge. Its port on that segment is the designated port.
Redundant-port blocking: Ports that would otherwise create a loop are placed in a non-forwarding state.
Topology-change handling: If a link or bridge fails, BPDUs trigger recalculation, and blocked ports may transition to forwarding.
BPDUs are exchanged over Layer 2 control frames. They are normally sent to the reserved multicast address 01:80:C2:00:00:00 and are not forwarded by normal bridge learning rules.
Small Example
Suppose switches A, B, and C form a triangle:
A—B
A—C
B—C
If A has the lowest bridge identifier, it becomes the root. B and C each select an appropriate port toward A. The remaining port on the B—C link is blocked because forwarding it would create a loop.
If the A—B link later fails, STP detects the topology change, unblocks the previously blocked port, and recalculates the tree. This provides redundancy without allowing both paths to forward simultaneously.
STP Protocol Evolution
Protocol
Standard
Main characteristic
STP
IEEE 802.1D
Original spanning-tree algorithm; convergence can be relatively slow
RSTP
IEEE 802.1w
Faster convergence using proposal and agreement mechanisms
PVST+
Cisco extension
Runs a separate STP instance for each VLAN
MSTP
IEEE 802.1s
Maps multiple VLANs into a smaller number of spanning-tree instances
Modern enterprise networks commonly use Rapid STP or Rapid PVST+ rather than classic STP. RSTP adds faster state transitions and features such as edge ports, but these do not eliminate the need for correct design.
Trade-offs and Best Practices
Redundancy versus convergence: STP enables redundant links, but classic STP may take longer than RSTP to react to failures.
Per-VLAN overhead: PVST+ provides granular VLAN balancing but can consume more control-plane resources. MSTP reduces overhead by grouping VLANs.
Do not enable edge ports indiscriminately: A port connected to an unmanaged switch or hub may introduce an unexpected loop. It should be configured as an edge only when that is safe.
Use root guard: Root guard prevents an attached edge device from influencing the root-bridge election.
Use BPDU guard: BPDU guard can disable an edge port if unexpected BPDUs indicate that an unauthorized or misconnected switch is attached.
Plan deliberately: Assign the root bridge using an appropriate bridge priority and keep links between access and distribution layers structured. STP should provide controlled redundancy, not repair an arbitrary physical topology.
22
What is an IP address and how is IPv4 structured?
KnownRevise
An IP address is a logical identifier assigned to a network interface, allowing hosts and routers to exchange packets using the Internet Protocol. IPv4 represents each address as a 32-bit value, usually written in dotted-decimal notation such as 192.0.2.10.
Read full answerHide full answer
Applies toIPv4 and general TCP/IP networking
Purpose of an IP Address
An IP address provides two related functions:
Source identification: identifies the interface sending a packet.
Destination addressing: allows routers to forward the packet toward the destination interface.
It identifies a network endpoint at the IP layer; it does not necessarily identify a physical device, application, or user. One host can have multiple IP addresses on different interfaces.
At the network layer of the OSI model, IP provides best-effort delivery. It offers addressing and routing but does not guarantee delivery, ordering, or duplicate-free transmission. TCP provides those reliability features when required.
IPv4 Address Structure
An IPv4 address contains 32 bits, divided into two logical parts:
Network prefix: identifies the network to which the address belongs.
Host portion: identifies a particular interface within that network.
The split is expressed using CIDR notation. For example, 192.0.2.10/24 means that the first 24 bits identify the network and the remaining 8 bits identify the host. In binary, the network prefix is 11000000.00000000.00000000, and the host portion is 00001010.
In dotted-decimal form, the network address is 192.0.2.0, the address itself is 192.0.2.10, and the directed broadcast address is 192.0.2.255.
The corresponding subnet mask is 255.255.255.0. Applying it with a bitwise AND operation extracts the network prefix: 192.0.2.10 AND 255.255.255.0 = 192.0.2.0.
Older classful addressing divided addresses into fixed classes such as Class A, B, and C. Modern networks use CIDR prefix lengths, allowing subnet sizes to be selected according to actual requirements.
Worked Subnet Example
Consider 192.0.2.10/24:
Total address bits: 32.
Network bits: 24.
Host bits: 32 - 24 = 8.
Total addresses: 2^8 = 256.
Usable host addresses: 256 - 2 = 254.
Usable range: 192.0.2.1 through 192.0.2.254.
Network address: 192.0.2.0.
Broadcast address: 192.0.2.255.
The network and broadcast addresses are excluded from normal host assignment. This calculation assumes IPv4 without any additional exceptions or special-purpose subnet assignments.
Special and Private IPv4 Addresses
Address type
Example
Purpose
Private
10.0.0.0/8
Used inside an organization; not globally routed
Private
172.16.0.0/12
Used inside an organization; not globally routed
Private
192.168.0.0/16
Used inside homes and small networks
Loopback
127.0.0.1
Refers to the local host itself
Link-local
169.254.0.0/16
Used for limited local communication, including DHCP fallback
Documentation
192.0.2.0/24
Reserved for documentation and examples
Private addresses are commonly translated to public addresses by Network Address Translation (NAT). Public IPv4 address exhaustion has therefore encouraged deployment of IPv6, which uses 128-bit addresses.
Addressing Versus DNS Names
IP addresses support network routing, while domain names such as example.com are easier for people to remember. DNS translates names into IP addresses, although applications may obtain addresses through other mechanisms such as DHCP.
On Linux, ip addr show displays interface addresses and prefix lengths, while ip route shows routes and the prefixes used to reach destination networks. IPv4 remains widely deployed, but new network designs increasingly use IPv6 alongside—or instead of—IPv4.
23
Why did CIDR replace classful addressing?
KnownRevise
CIDR (Classless Inter-Domain Routing) replaced classful IPv4 allocation because variable-length prefixes matched organizations’ actual address needs and enabled route aggregation. This reduced address waste and the number of entries required in the global routing table without changing the 32-bit IPv4 address format.
The original classful IPv4 scheme determined a unicast network’s class from its leading bits. Classes A, B, and C had fixed default subnet masks:
Class
Leading bits
First-octet range
Default mask
Network bits
Host bits
A
0
1–126
/8
8
24
B
10
128–191
/16
16
16
C
110
192–223
/24
24
8
D
1110
224–239
Multicast; not host-addressable
—
—
E
1111
240–255
Reserved/experimental
—
—
The 0/8 and 127/8 ranges were also reserved for special purposes and were not ordinary Class A networks.
For example, 192.168.1.10 belonged to the historical Class C range. With mask 255.255.255.0, the network address was 192.168.1.0, leaving eight host bits and providing 2^8 - 2 = 254 conventional usable host addresses.
Organizations received allocations based on these fixed classes rather than their precise needs. A Class B organization needing only 100 addresses would normally receive a /16 allocation and subdivide it internally rather than obtain a /25 directly from the classful allocation hierarchy.
Why Classful Addressing Became Inefficient
Address waste: Fixed class boundaries could give an organization far more addresses than it required, consuming a scarce global resource.
Routing-table growth: The Internet contained many individually allocated networks. When they could not be summarized under the classful hierarchy, routers needed separate routes, increasing forwarding-table size and routing-processing overhead.
CIDR permits aggregation across old class boundaries. For example, within one routing domain, the private networks 172.16.0.0/16, 172.17.0.0/16, 172.18.0.0/16, and 172.19.0.0/16 can be summarized as 172.16.0.0/12 when routing policy and reachability permit a common next hop. The /12 crosses the former Class B /16 boundaries and could not be represented as one classful aggregate.
If the individual /16 networks have different next hops, their more-specific routes are still required. An aggregate route can coexist with them, but it cannot by itself preserve distinct forwarding decisions.
CIDR and Worked Example
CIDR expresses the boundary between network and host bits using a prefix length. For 192.168.1.0/24:
The first 24 bits identify the network prefix.
The remaining eight bits identify hosts.
The corresponding mask is 255.255.255.0.
The block contains 2^8 = 256 total addresses.
A conventional subnet has 256 - 2 = 254 usable host addresses.
For 192.168.1.64/26:
Network prefix: 26 bits
Host bits: 32 - 26 = 6
Total addresses: 2^6 = 64
Conventional usable host addresses: 64 - 2 = 62
CIDR therefore allows allocations such as /20, /24, /26, or /29 according to actual requirements rather than only /8, /16, or /24.
Routing Behavior
CIDR is classless because a router no longer infers a network boundary from the address’s leading bits. The prefix length comes from the route configuration or routing-protocol advertisement.
Classless routing protocols carry prefix lengths or masks. BGP, OSPFv2, and IS-IS support classless routes, while RIPv1 was a historical classful exception; RIPv2 added mask support.
When multiple forwarding-table routes match a destination, the router uses longest-prefix match. For 192.168.1.100, a route to 192.168.1.0/24 is more specific than one to 192.0.0.0/8, so the /24 route is selected. Routing protocols first perform their own route selection; longest-prefix matching then determines which selected route is used for forwarding.
Textbook Model Versus Real Systems
Modern IPv4 systems do not treat addresses as permanently belonging to Class A, B, or C. An address’s network size depends on its prefix length in the relevant route or configuration.
Linux, Windows, and other current systems use classless route tables and longest-prefix matching. Linux’s ip route command displays CIDR-style prefixes. traceroute helps inspect the path to a destination but usually shows hop addresses rather than prefix lengths; dig performs DNS queries and does not display an IP prefix mask.
Historical Class A, B, and C terminology remains useful for understanding early IPv4 allocation, but it should not be used to infer the size of a modern network without its prefix length. IPv6 independently uses variable-length prefixes, commonly /64 subnets, and also uses CIDR-style notation.
24
What is subnetting, and why do networks use it?
KnownRevise
Subnetting is the practice of dividing an IP network into smaller logical networks called subnets by assigning different subnet prefixes to different parts of an organization. It improves address allocation, reduces unnecessary broadcast traffic, and enables hierarchical routing.
Read full answerHide full answer
Applies toIPv4 and IPv6 addressing
How It Works
In the OSI model, subnetting operates primarily at the network layer, where IP addresses and subnet prefixes determine how packets are routed. A subnet mask or prefix length identifies which part of an IPv4 address represents the network and which part represents the host.
For IPv4, a prefix such as /24 uses:
24 network bits: identify the network and subnet.
8 host bits: identify individual devices in that subnet.
The subnet mask for /24 is 255.255.255.0. A device uses the mask to determine whether another address is local or remote. If the destination is remote, it sends the packet to its default gateway rather than directly to the destination device.
Worked Example
Suppose an organization receives the IPv4 network 192.168.10.0/24 and divides it into /26 subnets.
Change the prefix:/24 to /26 borrows 2 host bits for subnetting.
Calculate the block size:256 - 2^6 = 192, so addresses increment by 192.
List the subnets:
Subnet
Network address
Usable host range
Broadcast address
1
192.168.10.0/26
192.168.10.1–192.168.10.62
192.168.10.63
2
192.168.10.64/26
192.168.10.65–192.168.10.126
192.168.10.127
3
192.168.10.128/26
192.168.10.129–192.168.10.190
192.168.10.191
4
192.168.10.192/26
192.168.10.193–192.168.10.254
192.168.10.255
A /26 subnet has 2^(8-2) = 64 total addresses. Two are reserved for the network and broadcast addresses, leaving 62 usable host addresses.
Why Networks Use Subnetting
Efficient address allocation: Large address blocks can be divided according to departmental, geographic, or functional needs.
Hierarchical routing: Routers aggregate traffic toward larger prefixes instead of requiring a separate route for every host.
Smaller IPv4 broadcast domains: In the IPv4 textbook model, broadcasts remain within a subnet, reducing unnecessary broadcast traffic.
Network organization: Separate subnets can represent offices, campuses, server farms, or tenant networks.
Policy separation: Administrators can apply routing, firewall, and access-control rules between subnets.
Future growth: A carefully selected prefix reserves enough host addresses for expansion without wasting address space.
Textbook Model Versus Real Systems
In a simplified textbook network, a subnet is often treated as a separate physical network connected through routers. In real systems, subnets are logically separated. A single physical switched infrastructure may carry several VLANs, with each VLAN commonly assigned to a distinct IP subnet and routed through Layer 3 interfaces. Virtual networks can also span multiple physical locations.
Linux interfaces store an address together with its prefix length, for example 192.168.10.65/26. Cloud platforms similarly use virtual private clouds or equivalent constructs to provide private subnets and controlled routing between them.
Subnetting does not automatically provide strong security: devices within the same subnet may communicate directly, while inter-subnet traffic can be inspected or blocked at a router or firewall. Traditional IPv4 subnets reserve network and broadcast addresses, although /31 point-to-point links under RFC 3021 and /32 host routes are special cases. IPv6 uses prefix-based subnetting but has no subnet broadcast address; it uses unicast, anycast, and multicast instead.
25
How many subnets and hosts does 192.168.1.0/26 provide?
KnownRevise
A /26 subnet contains 64 IPv4 addresses, of which 62 are normally usable for hosts. When dividing its parent network, 192.168.1.0/24, into /26 subnets, the result is 4 subnets with 62 usable host addresses per subnet.
Read full answerHide full answer
Applies toIPv4 CIDR subnetting in all IP stacks
Step-by-Step Calculation
The prefix /26 means that 26 of the 32 bits identify the network, leaving:
Host bits:32 - 26 = 6
Total addresses per subnet:2^6 = 64
Usable host addresses:64 - 2 = 62
The two excluded addresses are:
Network address:192.168.1.0 for the first subnet
Broadcast address:192.168.1.63 for the first subnet
The subnet count depends on the parent prefix. Assuming the parent is 192.168.1.0/24:
Additional subnet bits:26 - 24 = 2
Number of /26 subnets:2^2 = 4
Resulting Subnets
Subnet
Network address
Usable host range
Broadcast address
Usable hosts
1
192.168.1.0/26
192.168.1.1–192.168.1.62
192.168.1.63
62
2
192.168.1.64/26
192.168.1.65–192.168.1.126
192.168.1.127
62
3
192.168.1.128/26
192.168.1.129–192.168.1.190
192.168.1.191
62
4
192.168.1.192/26
192.168.1.193–192.168.1.254
192.168.1.255
62
The address 192.168.1.255 is the broadcast address of the final /26, even though it is also the broadcast address of the parent /24. This overlap is valid because broadcast domains are determined by the subnet mask.
Important Interpretation
If 192.168.1.0/26 is considered by itself, it represents one /26 subnet containing 62 usable host addresses. The answer of 4 subnets applies when it is used to subdivide the common parent network 192.168.1.0/24.
Practical Trade-Off
Using /26 masks creates smaller broadcast domains than a single /24, which can improve network organization and reduce unnecessary broadcast traffic. The trade-off is lower address utilization because each subnet reserves one network address and one broadcast address, wasting two addresses regardless of the subnet’s size.
26
How to calculate the network address from an IP address and subnet mask?
KnownRevise
A subnet mask is a 32-bit number that separates an IPv4 address into a network identifier and a host identifier; the network address is obtained by performing a bitwise logical AND between the IP address and the subnet mask. This operation zeros out the host bits, leaving only the network prefix.
Format: The subnet mask consists of a contiguous block of 1 bits followed by 0 bits; the 1 bits correspond to the network portion, the 0 bits to the host portion.
Representation: Common masks are written in dotted decimal (e.g., 255.255.255.0) or CIDR notation (e.g., /24).
Impact: The number of 1 bits determines the size of the network and the number of possible hosts.
Dotted decimal
CIDR
Network bits
Usable hosts (approx.)
255.0.0.0
/8
8
~16.7 million
255.255.0.0
/16
16
65,534
255.255.255.0
/24
24
254
255.255.255.252
/30
30
2
Calculating the Network Address
Convert both the IP address and the subnet mask to their 32-bit binary representations.
Perform a bitwise AND operation: for each bit position, the result is 1 only if both bits are 1.
Convert the resulting binary number back to dotted decimal; this is the network address.
The formula is: network_address = ip_address & subnet_mask (bitwise AND).
Worked Example
Take IP address 192.168.3.50 and subnet mask 255.255.255.0 (or /24).
IP in binary: 11000000.10101000.00000011.00110010
Mask in binary: 11111111.11111111.11111111.00000000
Bitwise AND: 11000000.10101000.00000011.00000000
Result in decimal: 192.168.3.0
Thus the network address is 192.168.3.0; the host portion is .50.
Code Example (Python)
The standard library ipaddress module can compute the network address automatically:
The strict=False flag allows host bits to be set in the supplied address; without it, IPv4Network would raise an exception.
Best Practices and Common Pitfalls
Always use contiguous masks; non-contiguous masks are invalid in modern TCP/IP stacks.
The network address itself is usually not assignable to an interface (except /32); the first usable host is typically network_address + 1.
CIDR notation simplifies subnetting and is the standard in routing tables and configuration files.
When designing a network, calculate the required number of hosts per subnet to choose an appropriate mask.
27
What are private IP addresses and reserved IPv4 address ranges?
KnownRevise
Private IP addresses are used inside private networks and are not globally routable on the public Internet. Reserved address ranges have standardized special purposes, so they should not be assigned as ordinary host addresses unless their defined role permits it.
Read full answerHide full answer
Applies tocomputer networks (IPv4 and IPv6 addressing)
Private IPv4 Address Ranges
The Internet Assigned Numbers Authority (IANA) recognizes three private IPv4 blocks defined by RFC 1918:
CIDR block
Address range
Typical use
10.0.0.0/8
10.0.0.0–10.255.255.255
Large enterprise, cloud, and service-provider networks
172.16.0.0/12
172.16.0.0–172.31.255.255
Medium-sized private networks
192.168.0.0/16
192.168.0.0–192.168.255.255
Home networks and small business networks
These addresses can be reused independently in different private networks. A typical home network might use 192.168.1.0/24, with 192.168.1.1 assigned to the router and 192.168.1.100 assigned to a laptop.
Routers normally provide Internet access using Network Address Translation (NAT), often combined with Port Address Translation (PAT). The router translates private source addresses and transport-layer port numbers to a public address and set of ports.
Other Special-Purpose IPv4 Ranges
The following ranges have specialized or restricted purposes:
CIDR block
Purpose
0.0.0.0/8
“This network” or current-network references; 0.0.0.0 also represents an unspecified source address in some contexts
127.0.0.0/8
IPv4 loopback; conventionally 127.0.0.1
169.254.0.0/16
Link-local addressing, including IPv4 Address autoconfiguration
100.64.0.0/10
Shared address space for carrier-grade NAT deployments
192.0.0.0/24
IETF protocol assignments, with several more-specific exceptions
192.0.2.0/24
Documentation example network, known as TEST-NET-1
198.51.100.0/24
Documentation example network, known as TEST-NET-2
203.0.113.0/24
Documentation example network, known as TEST-NET-3
198.18.0.0/15
Network benchmarking
224.0.0.0/4
IPv4 multicast
240.0.0.0/4
Reserved for future use; not a normal unicast allocation
255.255.255.255
Limited broadcast address
The exact assignments are maintained in the IANA IPv4 Special-Purpose Address Registry. “Reserved” is broader than “private”: a reserved range may be multicast, documentation-only, protocol-specific, or unavailable for general assignment.
IPv6 Equivalents
IPv6 uses different address blocks for equivalent purposes:
IPv6 block
Purpose
fc00::/7
Unique Local Addresses (ULAs), comparable to RFC 1918 private addressing
fe80::/10
Link-local unicast addresses
::/128
Unspecified address
::1/128
Loopback address
2001:db8::/32
Documentation prefix
ff00::/8
IPv6 multicast
A typical IPv6 ULA might use fd00::/8; however, the complete ULA allocation is fc00::/7. Unlike IPv4 link-local addresses, ULAs are not automatically derived from a physical link and are intended for internal network use.
Important Distinctions
Private is not the same as hidden: traffic using private addresses does not normally cross the public Internet, but private addressing itself provides no confidentiality or authentication.
Publicly routable does not mean publicly reachable: firewalls, routing policy, and ingress filtering can still block a globally routable address.
Loopback traffic stays on the host: it does not normally enter a physical network.
Multicast addresses are not host unicast addresses: they identify groups of receivers.
Documentation addresses are examples only: they should never be used for an operational endpoint.
Operating systems may impose additional restrictions: Linux, Windows, and network appliances can implement extra filtering rules beyond the IANA registry.
Practical Guidance
When designing an internal network, choose a private block that does not conflict with existing sites, then divide it into appropriate subnets. For example, 192.168.0.0/16 could be split into 192.168.1.0/24, 192.168.2.0/24, and additional /24 networks.
Use ip address on Linux to inspect local addresses and ip route to inspect routing decisions. Organizations should also plan for IPv6: relying only on IPv4 private addressing does not remove the need for IPv6 firewalling and network design.
28
What are the main types of Network Address Translation?
KnownRevise
Network Address Translation (NAT) translates IP addresses—and sometimes transport-layer port numbers—between different network address spaces. It is primarily used in IPv4 networks to let multiple private devices share a single public IPv4 address.
Read full answerHide full answer
Applies tocomputer networks and all common IPv4 Internet stacks
How NAT Works
A NAT-capable router or gateway maintains a translation table mapping internal connections to external addresses. For example, when a device at 192.168.1.10 connects to a server, the router replaces its private source address with its public address.
The router then rewrites:
The IP source address in the outgoing packet.
The IP checksum, because the source address changed.
The TCP or UDP source port when port translation is used.
The transport-layer checksum, because the IP address or port changed.
When the response arrives, the router uses the translation table to restore the destination information and forward the packet to the correct internal device. This is a stateful operation: NAT tracks mappings while connections are active.
NAT operates mainly at the network layer, while PAT also depends on transport-layer information from TCP or UDP. It does not replace a firewall; many routers implement NAT and packet filtering as separate features.
Main Types of NAT
Type
Address allocation
Typical use
Example
Static NAT
One private address permanently maps to one public address
Public services requiring a stable address
203.0.113.10 always maps to 192.168.1.10
Dynamic NAT
A private address receives an address from a configured public pool
Hosts that occasionally need public access
203.0.113.20 is temporarily assigned from a pool
PAT
Many private addresses share one public IP using different port numbers
Home routers and most consumer Internet access
203.0.113.1:40001 maps to 192.168.1.10:50000
Carrier-grade NAT
Many subscribers share public addresses through ISP infrastructure
IPv4 exhaustion at ISP level
Thousands of customers share a smaller public pool
NAT64
IPv6-only clients translate IPv4 destinations through a NAT64 gateway
IPv6-only networks accessing IPv4 services
An IPv6 client connects to an IPv4 server
In the usual textbook classification, static NAT, dynamic NAT, and PAT are the three primary types:
Static NAT: Each internal host has a fixed public mapping.
Dynamic NAT: Internal hosts receive temporary public addresses from a pool.
PAT: Multiple hosts share one public IP by distinguishing connections with translated transport-layer ports. PAT is also called NAT overload.
NAT64 is different: it translates between IPv6 and IPv4 address families rather than merely mapping private IPv4 addresses to public IPv4 addresses.
Concrete Example
Suppose a home network uses 192.168.1.0/24, and the router has the public address 203.0.113.1.
Two devices make outgoing connections:
Internal connection
Public representation seen by the server
192.168.1.10:50000 → 198.51.100.8:443
203.0.113.1:40001 → 198.51.100.8:443
192.168.1.20:60000 → 198.51.100.8:443
203.0.113.1:40002 → 198.51.100.8:443
The different public port numbers allow the router to return each response to the correct device.
Advantages and Limitations
Reduces IPv4 address consumption: An entire private network can use one or a small number of public IPv4 addresses.
Simplifies routing design: Private hosts can use a common internal addressing scheme.
Provides basic address concealment: External hosts do not directly receive the private source addresses, though NAT alone is not a security control.
NAT also introduces significant limitations:
State is required: The gateway must maintain mappings and handle timeouts.
Peer-to-peer applications may be affected: Incoming connections require explicit forwarding, static mapping, or protocol-specific mechanisms.
Some protocols are problematic: Applications embedding IP addresses in payloads or relying on fixed port numbers may fail without ALG or application-aware support.
Logging and troubleshooting become harder: Logs identify public mappings rather than direct internal users unless the NAT device records internal addresses.
It does not provide encryption: TLS or a VPN is needed to protect traffic confidentiality.
It can complicate IPv6 deployment: IPv6 supports globally scoped addressing without address-conservation NAT, but global reachability still depends on prefix delegation and routing.
Practical Guidance
Use RFC 1918 private IPv4 ranges internally: 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16.
Use static NAT when an externally reachable service needs a predictable public address.
Use dynamic NAT or PAT for ordinary outbound Internet access.
Remember that CGNAT may prevent inbound connections, even when port forwarding is configured on the customer router.
Do not describe NAT as a complete security solution; combine it with a properly configured firewall.
29
How does IPv6 differ from IPv4 in networking?
KnownRevise
IPv6 is a newer Internet Protocol designed to replace IPv4, primarily because public IPv4 address allocations are largely exhausted and its header offers limited extensibility. IPv6 uses 128-bit addresses, simplifies packet processing, and supports automatic address configuration, while IPv4 commonly relies on NAT for address conservation.
Read full answerHide full answer
Applies tocomputer networking (all versions of IPv4 and IPv6)
Key Differences
Feature
IPv4
IPv6
Address size
32 bits
128 bits
Theoretical address space
About 4.3 billion
About (3.4 times 10^{38})
Typical notation
192.0.2.10
2001:db8::10
Header size
Variable: 20–60 bytes
Fixed: 40 bytes
Header checksum
Present
Removed
Packet fragmentation
Routers or source may fragment
Only the source may fragment
Configuration
Usually manual or DHCP
SLAAC, DHCPv6, or both
Address translation
NAT is widely used
NAT is normally unnecessary
Traffic identification
Limited
Flow Label supports flow handling
Deployment
Still widespread and supported
Growing and supported by modern systems
Addressing and Subnetting
IPv4 provides (2^{32}) possible addresses, while IPv6 provides (2^{128}). A typical IPv4 subnet such as 192.0.2.0/24 contains:
[ 2^{32-24} = 2^8 = 256 text{ addresses} ]
A similarly structured IPv6 subnet such as 2001:db8:1234::/64 contains:
[ 2^{128-64} = 2^{64} text{ addresses} ]
IPv6 commonly uses a /64 prefix because it supports efficient subnetting and allows hosts to generate addresses through SLAAC. Common IPv6 address categories include:
Global unicast: generally allocated from 2000::/3
Link-local: fe80::/10, used for communication on the local link
Multicast: ff00::/8
Loopback: ::1
Unspecified address: ::
Header and Packet Processing
The IPv6 base header has a fixed length of 40 bytes and provides a simpler processing path. Options that were encoded directly in the IPv4 header are represented through extension headers in IPv6.
IPv6 removes the IPv4 header checksum because transport and upper-layer checksums provide end-to-end error detection. This can reduce processing work in routers. Modern operating systems and network interface controllers also commonly use checksum offloading to avoid calculating some checksums in software.
IPv6 handles fragmentation differently:
IPv4: A router may fragment a packet when the outgoing interface has a smaller MTU and the packet’s Don't Fragment bit is not set.
IPv6: Routers never fragment packets. The source uses Path MTU Discovery and, when necessary, includes a Fragment extension header.
IPv6 requires every link to support an MTU of at least 1,280 bytes, although normal Ethernet-style links usually use an MTU of 1,500 bytes. Large IPv6 packets can use jumbograms, but they require explicit support throughout the path.
Configuration and Address Management
IPv4 hosts commonly obtain a configuration through DHCP, as shown by a typical exchange:
The client broadcasts a DHCP discovery message.
The DHCP server selects an address.
The server offers that address and configuration parameters.
The client requests the offered address.
The server confirms the lease.
IPv6 hosts can use SLAAC to create addresses without a DHCP server. A router advertises a prefix, and each host can combine that prefix with an interface identifier to generate addresses. IPv6 also supports DHCPv6, but it is not required for every network.
IPv4 networks frequently use NAT, allowing multiple private hosts to communicate through one public IPv4 address. IPv6 deployments commonly provide globally routable unicast addresses, so NAT is generally unnecessary. However, an IPv6 host can have only link-local or unique-local addresses, and NAT66 exists but remains uncommon. IPv6 does not automatically make a network secure; firewalls and access-control policies remain important.
Security and Deployment
Neither protocol is inherently secure by itself. Secure communication still depends on TLS, properly configured firewalls, secure routing, endpoint authentication, and current operating-system patches.
IPv6 addresses are hierarchical and can be tracked more directly across Internet service providers than shared IPv4 addresses behind NAT. This improves routing scalability but can also reduce the obscurity previously provided by NAT, although IPv6 privacy-extension addresses can limit stable per-host tracking. Filtering based on address ranges remains possible and is commonly implemented in Linux and commercial firewalls.
Modern networks generally support dual stack operation, allowing IPv4 and IPv6 traffic to operate simultaneously. DNS can publish both A records for IPv4 and AAAA records for IPv6, allowing HTTP and SMTP services to be reached over either family. Migration tools or tunnels can connect IPv6-only and IPv4-only networks. IPv4 remains supported by Linux, Windows, macOS, routers, and major cloud platforms, but IPv6 deployment continues to expand.
30
How are IPv6 addresses structured, and what does SLAAC do?
KnownRevise
IPv6 addressing divides a 128-bit address into a network prefix and host bits according to a prefix length; /64 subnets are conventional but not mandatory. Stateless Address Autoconfiguration (SLAAC) lets a host form an IPv6 address from a prefix advertised by a router without DHCPv6 assigning that address.
Read full answerHide full answer
Applies toIPv6 addressing (RFC 4291), SLAAC (RFC 4862, updated by RFC 8981), DHCPv6 (RFC 8415), and RDNSS (RFC 8106)
IPv6 Address Structure
An IPv6 address contains 128 bits, represented as eight 16-bit groups, each written with up to four hexadecimal digits. For example, 2001:db8:1234:5678::1 expands to 2001:0db8:1234:5678:0000:0000:0000:0001. The :: shorthand may replace one contiguous run of zero groups.
A prefix length identifies the boundary between the network prefix and the remaining host bits:
Network prefix: The leading bits selected by the prefix length.
Host bits: The remaining bits, normally used as an interface identifier.
Prefix length: Written after the address, such as 2001:db8:1234:5678::1/64.
A /64 is the customary subnet size for ordinary IPv6 LANs, giving (2^{128-64}=2^{64}) addresses per subnet. IPv6 does not universally require /64 prefixes, however; aggregation may use a /48, and an operator may delegate a /56 or other prefix.
Address Types and Scope
Address type
Prefix
Purpose
Global unicast
Currently allocated from 2000::/3
Globally scoped unicast addressing
Unique local
fc00::/7
Organization-local addressing; commonly generated as fd00::/8
Link-local
fe80::/10
Communication on the local link
Multicast
ff00::/8
One-to-many or many-to-many delivery
Loopback
::1/128
Communication with the local host
Anycast
No dedicated prefix
A unicast-format address assigned to multiple interfaces
The 2001:db8::/32 prefix is reserved for documentation by RFC 3849, so addresses beneath it are not globally routable. IPv6 supports hierarchical route aggregation, allowing a provider to advertise a large aggregate while delegating more specific prefixes to customers.
How SLAAC Works
A router sends an IPv6 Router Advertisement containing a prefix, prefix length, and an Autonomous (A) flag.
A host receives the advertisement and generates an interface identifier for an interface on that link.
The host combines the advertised prefix and interface identifier to create a tentative address.
The host performs Duplicate Address Detection (DAD) by sending an ICMPv6 Neighbor Solicitation for the tentative address.
If no conflicting claim appears, the host uses the address for normal IPv6 communication.
SLAAC address assignment is separate from default-router discovery. A Router Advertisement can independently provide a prefix and advertise routers through its Router Information options.
Interaction with DHCPv6 and DNS
The Router Advertisement M and O flags determine which additional mechanisms are requested:
M=1: DHCPv6 supplies address information, so SLAAC is not being used for address assignment.
M=0, O=1: DHCPv6 supplies other configuration, commonly DNS servers, while SLAAC supplies the address. This is commonly called stateless DHCPv6.
M=0, O=0: Configuration is fully stateless; SLAAC supplies addresses and the advertisement supplies the default router.
With M=1 and O=1, DHCPv6 supplies both address and other configuration. DNS can alternatively be advertised through the Router Advertisement DNS/RDNSS option defined by RFC 8106.
Worked Prefix-Delegation Example
Suppose an organization receives 2001:db8:1234:5600::/56 from its provider. The allocation contains (2^{128-56}=2^{72}) addresses and can be divided into 256 /64 subnets. Eight such subnets are:
2001:db8:1234:5600::/64
2001:db8:1234:5601::/64
2001:db8:1234:5602::/64
2001:db8:1234:5603::/64
2001:db8:1234:5604::/64
2001:db8:1234:5605::/64
2001:db8:1234:5606::/64
2001:db8:1234:5607::/64
A host on the first subnet could use 2001:db8:1234:5600::1234/64, where the final 64 bits are its interface identifier.
Operational Guidance and Pitfalls
Neighbor discovery: IPv6 uses the Neighbor Discovery Protocol over ICMPv6 instead of IPv4 ARP.
No broadcast: IPv6 has no broadcast address; link-wide control functions use multicast.
Prefix lifetimes: Router Advertisements include preferred and valid lifetimes. During renumbering, the old prefix should normally remain valid temporarily while the new prefix becomes preferred.
Privacy: RFC 8981 temporary addresses provide additional temporary public addresses and limit long-term use of a stable public address. A stable interface identifier may still exist and remain exposed.
Interface identifiers: Modified EUI-64 identifiers can be derived from a MAC address and may expose hardware identity; implementations can instead use opaque stable or temporary identifiers.
Security: SLAAC does not inherently authenticate an advertised prefix. Hosts accepting forged Router Advertisements may configure incorrect addresses or routes, so Router Advertisement filtering and appropriate link protection are important.
31
How does ICMP enable ping and traceroute to work?
KnownRevise
ICMP (Internet Control Message Protocol) is the network-layer control and error-reporting protocol used by IPv4 and extended by ICMPv6. Echo Request and Echo Reply messages support ping, while Time Exceeded and destination responses support traceroute. ICMP is best-effort and provides neither ports nor guaranteed delivery, ordering, or flow control.
Read full answerHide full answer
Applies toIPv4 and IPv6 (ICMPv4 per RFC 792 and RFC 1981; ICMPv6 per RFC 4443)
Protocol Basics and Message Types
ICMP operates at the OSI network layer, equivalent to the TCP/IP internet layer. ICMPv4 uses IP protocol number 1, while ICMPv6 uses number 58. Messages are identified by type and code fields and are encapsulated in IP packets.
Purpose
IPv4 type/code
ICMPv6 type/code
Echo Request
8/0
128/0
Echo Reply
0/0
129/0
Destination Unreachable
3; codes include 0 net, 1 host, 3 port
1; code 4 means port unreachable
Fragmentation Needed / Packet Too Big
3/4
1/0
Time Exceeded, TTL expired
11/0
3/0
Redirect
5
137
ICMPv6 is integral to IPv6 and also carries Neighbor Discovery and Path MTU Discovery messages. ICMPv4 supports Path MTU Discovery through Fragmentation Needed messages.
How ping Uses ICMP
The client sends an Echo Request containing an identifier, sequence number, and usually a timestamp or other payload.
The destination returns an Echo Reply, echoing the identifier, sequence number, and payload.
The client computes RTT from the send and receive timestamps and reports packet loss plus minimum, average, and maximum RTT. Linux iputils also reports mdev, a measure of RTT variation.
Identifier and sequence matching associates replies with outstanding requests and filters stale or unrelated replies. It does not authenticate the responder, so a forged reply can still match.
How traceroute Uses ICMP
The client sends probes with progressively increasing TTL values.
Each IPv4 router decrements the TTL. When it reaches zero, the router discards the packet and sends an ICMP Time Exceeded message to the source.
An IPv4 error contains the original IP header and first eight payload bytes, allowing the source to associate it with a probe. ICMPv6 includes as much of the original packet as possible without exceeding the minimum IPv6 MTU.
Intermediate routers reveal themselves through Time Exceeded responses. Their response times estimate the RTT to each hop.
In the common UDP mode, the destination normally reports that the port is unreachable: type 3/code 3 for IPv4 or type 1/code 4 for ICMPv6. Linux and BSD traceroute commonly use UDP by default; Windows tracert and Linux traceroute -I use ICMP Echo Requests and identify the destination from its Echo Reply.
Comparing and Observing the Tools
Aspect
ping
traceroute
Main ICMP messages
Echo Request/Reply
Time Exceeded plus Port Unreachable or Echo Reply
Purpose
Reachability, latency, and loss
Approximate per-hop path and RTT
Main mechanism
Identifier and sequence matching
Increasing IP TTL
Useful Linux commands include ping -c 4 8.8.8.8, traceroute -n 8.8.8.8, sudo traceroute -I -n 1.1.1.1, and sudo tcpdump -ni eth0 'icmp and host 8.8.8.8'. For an IPv4 1500-byte path-MTU test, ping -4 -M do -s 1472 example.com uses 1472 payload bytes plus a 20-byte IPv4 header and 8-byte ICMP header.
Security and Operational Considerations
Amplification: RFC 1122 recommends that hosts not answer Echo Requests sent to broadcast or multicast destinations. Rate limiting is important, and ICMP errors should not themselves become amplification sources.
Filtering: Firewalls may block Echo Requests or Time Exceeded messages. Missing replies can therefore indicate filtering rather than a failed path. Windows Firewall behavior varies by profile and enabled rule.
Path MTU discovery: Indiscriminately dropping Fragmentation Needed or Packet Too Big messages breaks Path MTU Discovery. Administrators should preserve these messages while rate-limiting other ICMP errors where appropriate.
Redirects: ICMP Redirect messages are commonly disabled because accepting untrusted redirects can enable routing attacks.
Multipath: ECMP or unequal-cost routing may send different probes over different paths, producing apparently inconsistent hop sequences. RFC 4884 and RFC 4950 define ICMP extensions for additional path information.
Best Practices
Use ping for reachability and loss, not bandwidth measurement; use iperf3 for throughput testing.
Treat traceroute as a diagnostic estimate rather than an authoritative routing table, and repeat it because routing and load-balancing policies can change.
Combine traceroute with mtr, tcpdump, and application-level measurements to distinguish filtering, packet loss, and path changes.
Monitor ICMP error rates and latency, while allowing the ICMP messages required for IPv4 and IPv6 Path MTU Discovery.
32
What are IP fragmentation and MTU in computer networking?
KnownRevise
IP fragmentation is the process of dividing an oversized IP packet into smaller fragments so they can traverse a link with a smaller maximum transmission unit (MTU). MTU is the maximum size of an IP packet that a link can carry without requiring fragmentation.
Read full answerHide full answer
Applies toall versions of IPv4, IPv6, TCP/IP, and Ethernet
MTU Fundamentals
MTU: The maximum size, in bytes, of an IP packet supported by a link or outgoing interface.
The MTU includes the complete IP header and any IPv6 extension headers, but excludes the link-layer header and trailer.
Standard Ethernet normally has an MTU of 1500 bytes. Other interfaces can differ: Linux loopback commonly supports much larger packets, while tunnels often expose smaller MTUs.
A packet can cross several links with different MTUs. The usable path MTU is effectively limited by the smallest MTU along the route.
How IPv4 Fragmentation Works
In IPv4, the source host or an intermediate router can fragment a packet when it exceeds the outgoing link’s MTU and the Don’t Fragment (DF) flag is not set.
A copy of the IP header is placed in each fragment, with fields such as total length, flags, fragment offset, and header checksum updated as necessary.
Each fragment must fit within the outgoing MTU. Except for the final fragment, its data length must be a multiple of 8 bytes.
The Fragment Offset identifies the fragment’s position in the original payload and is measured in 8-byte units.
The More Fragments (MF) flag indicates whether more fragments follow.
The destination host reassembles all fragments before delivering the datagram to the transport layer.
Fragments retain the same identification value, protocol, source address, and destination address. They begin with the same TTL, but routers decrement each fragment’s TTL independently, so their final TTL values can differ if they traverse different routes.
Worked Example
Suppose an IPv4 packet has a 4000-byte payload and a 20-byte header, giving a total size of 4020 bytes. With a 1500-byte outgoing MTU, the maximum data in each fragment is 1500 − 20 = 1480 bytes.
Fragment
Data size
Total IP size
Fragment offset
MF flag
1
1480 bytes
1500 bytes
0
1
2
1480 bytes
1500 bytes
185
1
3
1040 bytes
1060 bytes
370
0
The second offset is 1480 ÷ 8 = 185, while the third is 2960 ÷ 8 = 370. The original payload is recovered as 1480 + 1480 + 1040 = 4000 bytes.
MTU, MSS and Path MTU Discovery
Concept
Layer
Meaning
MTU
Network layer
Maximum complete IP packet size
TCP MSS
Transport layer
Maximum TCP segment payload a receiver is willing to accept
PMTUD
Network layer
Mechanism for discovering the smallest MTU along a path
On a typical 1500-byte path without additional IPv6 extension headers, the advertised MSS is:
Path MTU Discovery (PMTUD) avoids unnecessary fragmentation. In IPv4, a router that receives a packet larger than the next-hop MTU with DF set discards it and returns an ICMPv4 “Fragmentation Needed and DF Set” message. The sender then reduces its packet size, and TCP uses the discovered PMTU when sizing segments. In IPv6, routers never fragment; they return an ICMPv6 “Packet Too Big” message containing the required MTU information.
IPv4 and IPv6 Differences
Feature
IPv4
IPv6
Router fragmentation
Permitted when DF is clear
Never permitted
Source fragmentation
Allowed
Allowed using fragmentation extension headers
Oversized-packet feedback
ICMPv4 fragmentation-needed message
ICMPv6 Packet Too Big message
PMTUD
Commonly used
Mandatory IPv6 source-side behavior
Fragmentation adds overhead because every fragment requires its own IP header. It also increases packet count, requires reassembly resources, and can enable packet-loss denial-of-service or overlapping-fragment attacks. Modern systems therefore generally prefer PMTUD and appropriately sized TCP segments.
Practical Guidance and Pitfalls
Prefer working PMTUD over routinely disabling DF or reducing every interface’s MTU.
Check local interface settings with Linux ip link show.
With Linux iputils ping, -M do sets the IPv4 DF flag. ping -M do -s 1472 1.1.1.1 requests a 1500-byte IPv4 packet, whereas ping -M do -s 1473 1.1.1.1 requests 1501 bytes.
The second ping should report an MTU-related failure when the path MTU is 1500 and the required ICMP error reaches the client. Reachability and ICMP filtering can affect both results.
tracepath may reveal path-MTU information when it is installed and permitted by the network.
33
How does routing work when forwarding packets through an IP network?
KnownRevise
Routing is the process of selecting a path for an IP packet and forwarding it toward its destination. A router performs this function at the network layer by examining the packet’s destination IP address, choosing the most specific matching route, and sending the packet to the next hop.
Read full answerHide full answer
Applies tocomputer networks (IPv4 and IPv6; Linux and general TCP/IP stacks)
Routing Versus Forwarding
Routing: Determining which paths are available and learning routes through static configuration or routing protocols such as OSPF and BGP.
Forwarding: Moving an individual packet along the already selected route.
Next hop: The router or directly connected destination to which the router sends the packet.
Routing and forwarding are closely related, but real routers separate them into two planes:
Control plane: Runs routing protocols and determines the routing table.
Data plane: Uses a forwarding table, often implemented in specialized hardware, to process packets at high speed.
How a Router Forwards a Packet
A router generally performs these steps:
Receive the frame: The router removes the incoming link-layer frame, such as an Ethernet frame.
Inspect the IP header: It reads the destination IP address, destination prefix, TTL, and other routing fields.
Check the destination:
If the destination is the router itself or a directly connected network, the packet is delivered locally.
Otherwise, the router forwards it toward another router.
Perform a longest-prefix match: It selects the route with the most specific destination prefix. A /24 route is preferred over a /16 route when both match.
Determine the next hop: The route identifies an outgoing interface and, usually, a next-hop IP address.
Decrement the TTL: The TTL is reduced by one. If it reaches zero, the router discards the packet and normally returns an ICMP Time Exceeded message.
Resolve the next-hop address: On Ethernet, the router uses ARP for IPv4 or Neighbor Discovery for IPv6 to find the next hop’s link-layer address.
Recalculate checksums and rewrite the frame:
In IPv4, the router recomputes the IP header checksum after decrementing the TTL.
IPv6 routers do not use an IPv6 header checksum.
The outgoing link-layer frame receives a new source MAC address for the outgoing interface and the next hop’s destination MAC address.
Transmit the packet: The router sends the new frame through the selected outgoing interface.
Each link-layer frame is valid only for one local link. Therefore, the IP destination can remain unchanged while the Ethernet source and destination addresses change at every hop.
Worked Forwarding Example
Suppose a Linux router has these routes:
Destination
Next hop
Interface
Type
10.1.0.0/24
Directly connected
eth0
Connected
192.168.0.0/16
192.168.1.1
eth1
Static
0.0.0.0/0
192.168.1.1
eth1
Default
For a packet destined for 10.1.2.5:
The destination belongs to the directly connected 10.1.0.0/24 network.
The router selects eth0.
It obtains the destination’s MAC address through ARP and encapsulates the packet in a new Ethernet frame.
It delivers the packet directly to 10.1.2.5.
For a packet destined for 8.8.8.8:
No specific route matches.
The router selects the default route 0.0.0.0/0.
It forwards the packet to 192.168.1.1 through eth1.
The default route is used only when no more-specific route matches. A longest-prefix lookup can be represented conceptually as:
Matching Route
Prefix Length
Selected
0.0.0.0/0
0
No
10.0.0.0/8
8
No
10.1.0.0/24
24
Yes
Route Sources and Real Systems
Static routes: Configured manually; predictable but operationally difficult in large networks.
Interior gateway protocols: OSPF and IS-IS operate within an autonomous system.
BGP: Exchanges routes between autonomous systems and supports policy-based path selection.
Connected routes: Automatically appear when an interface has an assigned address.
Policy routes: Select routes according to source address or other criteria.
Equal-cost paths: Some implementations balance traffic across multiple next hops.
On Linux, administrators inspect routing with ip route and query the selected path with ip route get <destination>. Packet traces using tcpdump can reveal outgoing interfaces and next-hop addresses, while traceroute helps observe the path through TTL-limited probes.
Trade-offs and Common Pitfalls
More-specific routes are not always better: Excessive route fragmentation increases memory use and lookup complexity.
Default routes improve reachability: They provide a fallback but can hide missing or incorrect internal routes.
TTL limits loops: It prevents packets from circulating indefinitely but does not replace correct routing.
Routing is not NAT: Forwarding normally preserves the original source and destination IP addresses. NAT is a separate gateway function that may translate addresses or ports.
Routing is not switching: Routers forward packets between different IP networks, while switches forward link-layer frames within a LAN.
Hardware differs from the textbook model: Textbook routers may appear to search one complete routing table. Modern routers usually maintain a control-plane routing table and a faster forwarding table optimized with ASICs or TCAM.
34
How do static routing and dynamic routing differ?
KnownRevise
Static routing uses manually configured routes, while dynamic routing learns routes automatically through routing protocols. Both approaches populate a router’s routing table, after which the router forwards packets using the most specific matching prefix.
A destination network or prefix, such as 192.168.10.0/24
A next-hop router or outgoing interface
Optional attributes, such as a metric, preference, or policy
Routers normally use longest-prefix matching: if a packet matches several routes, the route with the longest prefix is selected. For example, a route for 10.1.2.0/24 is preferred over a default route for 0.0.0.0/0.
The control plane determines which routes should exist, while the forwarding plane looks up routes and moves packets.
Static and Dynamic Routing Compared
Aspect
Static routing
Dynamic routing
Configuration
Routes are entered manually
Routes are learned through routing protocols
Topology changes
Require manual intervention
Detected and handled automatically
Protocol overhead
None
Routing updates consume bandwidth and CPU
Administrative effort
High for large or changing networks
Lower after initial configuration
Predictability
Highly predictable and under operator control
Depends on protocol metrics and policies
Convergence
No automatic protocol-based convergence
Supports automatic convergence, but not instantly
Scaling
Difficult for large networks
Designed to scale through hierarchical design
Common uses
Stub networks, small sites, fixed paths
Enterprise networks, Internet service providers, changing topologies
How Dynamic Routing Learns Routes
Dynamic routing protocols exchange information about reachable networks and select routes using protocol-specific rules:
Distance-vector protocols, such as RIP, advertise routes and their distances from the current router.
Link-state protocols, such as OSPF and IS-IS, build a topology database and run the shortest-path-first algorithm, usually Dijkstra’s algorithm.
Path-vector protocols, such as BGP, exchange routes with additional attributes and policies, including the autonomous system path.
After receiving updates, routers run their routing algorithms, compare candidate paths, and install the best routes according to metrics and policy. Timers, route filters, and route preferences influence this process.
Failure Handling and Convergence
Convergence occurs when routers in a network reach a consistent understanding of available paths. Dynamic routing can detect a failed link and replace routes with alternatives, but convergence takes time and depends on the protocol.
For example, suppose a router has two Internet connections:
A static default route points to ISP A.
BGP learns an alternative default route through ISP B.
If the ISP A connection fails, BGP can withdraw or deprioritize its route, allowing the ISP B route to become active. A purely static default route normally remains configured and is not automatically replaced unless a separate failover mechanism, such as interface tracking or an additional managed route, is used.
Dynamic routing is not guaranteed to recover instantly. Detection depends on keepalives, hello intervals, and failure-detection timers. Incorrect configuration, routing loops, route flapping, and incompatible policies can delay or prevent convergence.
Real-World Use
Real networks usually combine both methods. A Linux host might contain static routes alongside routes learned by a routing daemon such as FRR, which can implement protocols including OSPF, IS-IS, RIP, and BGP.
Environments where links and paths frequently change
Networks requiring redundant paths
Organizations that need automatic topology discovery
The best design is often hybrid: dynamic protocols handle broad reachability, while static routes provide controlled exceptions, management paths, or deliberate traffic steering.
35
How do distance-vector and link-state routing differ?
KnownRevise
Distance-vector routing and link-state routing are two ways routers discover paths through a network. Distance-vector routers exchange distance information with neighbors, while link-state routers build a shared map of the topology and independently calculate shortest paths.
Read full answerHide full answer
Applies tocomputer networks and Internet routing protocols
Core Distinction
Distance-vector routing
Each router maintains a distance to every known destination and the next hop used to reach it.
A router periodically sends its complete distance vector to directly connected neighbors.
Neighbors compare the received information with their own table and update it when they find a better path.
The classic algorithm is Bellman–Ford, which supports integer hop counts and can accommodate path costs.
RIP is the standard distance-vector example.
Link-state routing
Each router discovers its directly connected links and their costs.
It creates link-state advertisements (LSAs) describing that local topology and reliably floods them throughout the routing domain.
Every router receives the same link-state database and runs the shortest-path-first (SPF) algorithm, commonly Dijkstra’s algorithm.
OSPF and IS-IS are link-state examples.
Worked Example
Consider this topology:
A ----1---- B ----2---- C
The shortest path from A to C has total cost 3.
With distance-vector routing:
A initially knows only that B is directly reachable with cost 1.
B advertises that it can reach C with cost 2; A adds its own link cost to B, giving 1 + 2 = 3.
A installs the next hop B for destination C.
With link-state routing:
Each router advertises its local links: A advertises A-B with cost 1, and B advertises A-B and B-C with their costs.
All routers obtain the same topology database.
Each router runs SPF and independently determines that the path from A to C costs 3.
Both approaches can produce the same routing table, but they obtain and maintain the information differently.
Comparison
Property
Distance-vector routing
Link-state routing
Information exchanged
Complete distance vector
Link-state advertisements
Information sent to
Direct neighbors
Flooded across the routing domain
Path calculation
Bellman–Ford on received vectors
Dijkstra or another SPF algorithm
Topology knowledge
Only neighbors’ advertised distances
Shared view of the topology
Update pattern
Usually periodic
Triggered by topology changes
Routing-table size
One entry per destination
Destination entries plus link-state database
Convergence
Generally slower and vulnerable to loops
Generally faster and loop-free after synchronization
Failure handling
May require several update cycles
New LSAs trigger immediate recomputation
Scaling
Simple for small networks
Better suited to large networks
Example protocol
RIP
OSPF, IS-IS
Convergence and Failure Behavior
Distance-vector routing can suffer from the count-to-infinity problem when a link fails. Routers may temporarily believe that a failed destination is reachable through a longer path. Poisoned-reverse, split-horizon, hold-down, and route poisoning mechanisms reduce this problem, but do not eliminate every form of routing instability.
Link-state routing avoids this specific problem by flooding the changed link information and recomputing shortest paths from a consistent topology database. However, initial synchronization, flooding, SPF computation, and memory use require additional resources. OSPF limits flooding through areas, while IS-IS uses a hierarchical level design for large networks.
Practical Trade-offs
Distance-vector
Easy to implement and understand.
Works with little topology information.
Appropriate for small networks or legacy deployments.
RIP uses a maximum usable hop count of 15; metric 16 represents infinity.
Link-state
Provides faster convergence and more accurate metrics.
Supports hierarchical design and authentication.
Requires sufficient CPU and memory to maintain the link-state database and run SPF.
Requires adjacency establishment, reliable flooding, and careful area design.
In real Internet deployments, these algorithms usually operate inside an autonomous system rather than across the entire Internet. BGP is neither distance-vector nor link-state: it is a path-vector protocol that exchanges complete AS paths. Forwarding also differs from routing—routing selects the next hop, while the data plane forwards packets using that decision.
36
How does RIP routing work, and what is count-to-infinity?
KnownRevise
RIP (Routing Information Protocol) is a distance-vector routing protocol in which routers exchange distance vectors and select routes using hop count. Its count-to-infinity problem can occur when stale routing information sustains a forwarding loop, causing routers to advertise increasingly large metrics, potentially until RIP’s unreachable threshold of 16 is reached.
Read full answerHide full answer
Applies toRIP v2 for IPv4 (RFC 2453) and RIPng for IPv6 (RFC 2080); RIP v1 is discussed historically
How RIP Works
RIP applies the distance-vector algorithm, based on Bellman–Ford. Each router maintains a routing table containing, for every reachable destination:
The destination network or address.
The next-hop router.
The outgoing interface.
The metric, normally the number of hops.
Administrative information used by the implementation.
RIP v2 normally uses UDP port 520 and multicasts periodic updates to 224.0.0.9. Every 30 seconds, a router sends its distance vector to neighboring routers. The packet contains the destination address, subnet mask, next hop, and metric for each route.
When router A receives an update from neighbor B, it adds the cost of its link to B. For example:
Router
Current route to D
Received vector for D
New candidate route
A
Cost 4 via X
B advertises cost 2
Cost 3 via B
A
Cost 3 via B
B advertises cost 2
Keep cost 3
RIP selects the route with the lowest metric. A metric of 16 means unreachable, so valid RIP paths contain at most 15 hops.
RIP Update Process
A router initializes directly connected networks with metric 1.
It sends its current distance vector to its neighbors.
Each neighbor evaluates the advertised routes.
A better route replaces the existing route; an equal-cost route may be handled according to implementation-specific tie-breaking rules.
The router sends an update immediately when an important metric changes and repeats full updates every 30 seconds.
If a route is not refreshed for 180 seconds, RIP marks it invalid.
The full-table periodic update is simple, but it consumes bandwidth and converges more slowly than link-state protocols.
The Count-to-Infinity Problem
Consider the underlying distance-vector exchange before split horizon or poison reverse suppresses it. Suppose destination D becomes unreachable, but routers A and B retain stale routes that point to each other:
Router
Stale belief about D
A
D is cost 2 away through B
B
D is cost 3 away through A
Each router believes the other has a usable path and adds one to the other’s advertised metric. The metrics then increase through values such as 4, 5, 6, and so on, even though D is actually unreachable.
This happens because:
A router cannot immediately distinguish a valid neighbor’s route from stale information.
The two routers form a temporary forwarding loop.
Each update advertises a worse metric, but neither router knows that the information came indirectly from itself.
RIP can stop the process when a metric reaches 16 and the route is declared unreachable. Thus, count-to-infinity bounds the damage but may delay convergence.
Mitigations and RIP Versions
RIP uses several mechanisms to reduce the problem:
Split horizon: Do not advertise a route back to the neighbor from which it was learned.
Poison reverse: Advertise such a route with metric 16 to signal that it should not be selected.
Triggered updates: Send an update immediately after a significant metric change.
Hold-down: Temporarily reject worse routes for a destination after a route becomes invalid.
Infinity threshold: Reject or remove routes whose metric reaches 16.
These techniques reduce or break many loops, but they do not make RIP immune to every count-to-infinity scenario.
Version
Transport
Addressing
Main characteristics
RIP v1
UDP 520
Classful IPv4
Broadcast updates; no subnet masks; obsolete
RIP v2
UDP 520
Classless IPv4
Multicast updates; supports masks and next-hop information
RIPng
UDP 521
IPv6
Uses IPv6 addresses and next hops
Trade-offs and Real-World Use
RIP is easy to configure and has low router overhead, making it suitable for small, flat networks. Its main limitations are slow convergence, limited scalability, a 15-hop boundary, periodic bandwidth overhead, and weak protection against forged updates.
Production networks normally use OSPF for interior link-state routing or BGP for interdomain routing. Systems such as FRR and Cisco IOS still support RIP for compatibility and small deployments, while Linux routing commonly relies on the kernel and routing daemons such as FRR rather than a standard textbook RIP implementation. Security-sensitive RIPv2 deployments should use the authentication defined by RFC 5880 and network-layer access controls; RIPng deployments can use RFC 6610 authentication.
37
How does OSPF build and maintain its routing tables?
KnownRevise
OSPF (Open Shortest Path First) is a link-state interior gateway protocol (IGP). Routers form neighbor adjacencies, synchronize a link-state database (LSDB) for each area in which they participate, run Dijkstra’s shortest-path-first (SPF) algorithm, and install the resulting routes. Changes are maintained through flooded link-state advertisements (LSAs) and subsequent SPF recalculation.
Read full answerHide full answer
Applies toOSPFv2 for IPv4 (RFC 2328) and OSPFv3 for IPv6 (RFC 8362)
How OSPF Works
Neighbor discovery: Routers exchange Hello packets. Matching area IDs, timers, authentication settings, and other parameters determine which routers can form adjacencies.
Database synchronization: Neighbors exchange Database Description (DBD) packets, compare their LSDBs, and request missing LSAs.
LSA flooding: Each router originates LSAs describing its directly connected links and floods them within the appropriate scope.
SPF calculation: Every router uses its area’s LSDB to calculate shortest paths, primarily for intra-area destinations.
Route installation: The calculated destination prefixes, outgoing interfaces, and next hops are installed in the routing table.
Incremental maintenance: Changed LSAs are flooded and acknowledged. Routers then recalculate the affected routes, often using optimized or incremental SPF implementations rather than exchanging complete distance-vector updates.
Both OSPFv2 and OSPFv3 use IP protocol number 89.
Packets and Link-State Database
OSPF packet
Purpose
Hello
Discovers and maintains neighbors
DBD
Describes and compares LSDBs
LSR
Requests specific LSAs
LSU
Carries new or updated LSAs
LSAck
Acknowledges received LSAs
Common OSPFv2 LSA types include:
Router LSA: Describes a router’s links and interfaces within an area.
Network LSA: Represents the routers connected to a multiaccess network.
Summary LSA: Advertises networks between areas.
ASBR Summary LSA: Identifies reachable ASBRs.
AS External LSA: Advertises routes redistributed into OSPF.
NSSA External LSA (type 7): Carries external routes within a not-so-stubby area.
OSPFv3 uses different numeric LSA type values but has analogous router, network, inter-area, external, and NSSA-external LSAs. LSA flooding avoids periodic full-database exchanges, although topology changes can temporarily consume significant CPU and memory.
Areas and Router Roles
Area 0: The backbone area through which non-backbone areas normally connect.
Interior router: Participates in only one non-backbone area.
Area Border Router (ABR): Connects multiple areas and maintains an LSDB for each area.
Autonomous System Boundary Router (ASBR): Redistributes routes into or out of the OSPF autonomous system.
Stub area: Rejects type 5 external LSAs; a default route may be advertised instead.
NSSA: Permits type 7 external routes while preventing them from being propagated into ordinary stub areas.
On broadcast and NBMA network types, routers elect a Designated Router (DR) and Backup Designated Router (BDR). The DR reduces the number of full adjacencies and handles flooding on the shared network. Point-to-point network types do not require a DR.
SPF Calculation and Convergence
Assume reference bandwidth 100 Mbps. OSPF interface cost is approximately:
cost = reference bandwidth / interface bandwidth
Link
Bandwidth
OSPF cost
R1–R2
100 Mbps
1
R2–R3
50 Mbps
2
R1–R3
20 Mbps
5
R1’s direct path to R3 costs 5, while the path through R2 costs 1 + 2 = 3; therefore, OSPF prefers R2. If R2–R3 fails, R2 and R3 originate updated Router LSAs. After receiving them, R1 recalculates the shortest path and uses the direct route.
OSPF generally converges faster than distance-vector protocols such as RIP because each router has a topology database rather than only neighboring route summaries. Typical protocol defaults are a 10-second Hello interval and 40-second Dead interval, although implementations and configurations can differ.
After SPF, normal route-selection rules still apply:
A route from a protocol with a better administrative distance may replace the OSPF route.
Many implementations install equal-cost paths.
Passive interfaces suppress Hello exchanges and neighbor formation.
Prefix summarization reduces the routes propagated across an area boundary.
Trade-offs and Operations
Advantage
Trade-off
Fast, topology-aware convergence
Requires more memory and SPF CPU than distance-vector protocols
Hierarchical areas improve scalability
Requires careful area and prefix design
Only changed LSAs are flooded
Large areas can create considerable LSA churn
Supports neighbor authentication
OSPF does not itself encrypt routing information
Cisco, Juniper, Arista, and FRR implement OSPF with different extensions, policies, timer defaults, and authentication options. Linux commonly uses the FRRouting daemon rather than implementing OSPF in the kernel. Useful commands include show ip ospf neighbor, show ip ospf database, show ip ospf interface, vtysh, and tcpdump.
Security and Best Practices
Use a hierarchical area design and provide every non-backbone area with connectivity to area 0.
Authenticate neighbors with the strongest HMAC mechanism supported by the platform; avoid legacy plain-text authentication.
Protect the routing control plane with suitable packet filters, control-plane policing, and secure management access.
Summarize prefixes at area boundaries where appropriate.
Monitor neighbor states, LSDB size, SPF runtimes, CPU utilization, and authentication failures.
Verify interface types, costs, timers, and DR/BDR state before changing adjacency settings.
38
What is BGP and why is it crucial for internet routing?
KnownRevise
Border Gateway Protocol (BGP) is the de facto interdomain routing protocol used by autonomous systems (ASes) to exchange reachability and policy information for IP prefixes. It is crucial because it allows independently administered networks to learn how to reach one another while selecting routes according to operational and commercial policy rather than a single global optimum.
Read full answerHide full answer
Applies toInternet routing with BGP-4 (RFC 4271), MP-BGP (RFC 4760), and related BGP address-family extensions
What BGP Is
BGP is a path-vector routing protocol used between and within autonomous systems.
eBGP exchanges routes between different ASes; iBGP exchanges routes between BGP speakers inside one AS.
BGP-4 is the current base version. Multiprotocol BGP extends BGP to additional address families such as IPv6 unicast and multicast. VPNv4, VPNv6, and EVPN use separate address-family extensions built on BGP.
BGP operates over TCP port 179, which provides reliable, ordered delivery of BGP messages.
How BGP Works
Establish a session: Two BGP speakers connect over TCP and exchange OPEN messages to negotiate capabilities and supported address families. They then exchange KEEPALIVE messages to maintain the session.
Advertise reachability:UPDATE messages carry network-layer reachability information, such as prefixes, along with path attributes and withdrawals.
Select a route: A BGP speaker evaluates candidate routes using local policy and path attributes. Common criteria include:
Highest LOCAL_PREF
Shortest AS_PATH
Lowest ORIGIN value: IGP, then EGP, then incomplete
Lowest MED, normally compared only for routes learned from the same neighboring AS unless the implementation is configured otherwise
eBGP over iBGP
Lower IGP metric to the next hop
Implementations also use tie-breakers such as route age and router ID. Cisco’s Weight attribute is proprietary and is evaluated before the common criteria. 4. Advertise according to policy: Route maps, prefix lists, AS-path filters, local preferences, and communities can cause different routes to be advertised to different peers. With the ADD-PATH capability, multiple paths can be advertised. 5. Propagate within the AS: iBGP does not automatically advertise a route learned from one iBGP peer to another iBGP peer. Full-mesh iBGP is common, while route reflectors can reduce the peering requirements.
BGP uses a finite-state machine with the states Idle, Connect, Active, OpenSent, OpenConfirm, and Established. The AS_PATH attribute lets a router reject a route whose path already contains its own AS, preventing an AS-level routing loop.
Why BGP Is Critical
Concern
BGP
Typical IGP such as OSPF
Scope
Primarily between ASes; also used inside an AS
Within one AS
Primary purpose
Exchange interdomain reachability and policy
Find internal paths between routers
Route selection
Strong emphasis on administrative policy
Primarily based on topology metrics
Typical use
eBGP and iBGP
OSPF, IS-IS, or EIGRP inside an AS
Interoperability: BGP provides the common routing protocol between independently operated networks, ISPs, enterprises, and Internet exchanges.
Policy control: Operators can prefer certain providers, protect transit relationships, restrict prefixes, and steer traffic using attributes such as LOCAL_PREF, AS_PATH prepending, and communities.
Traffic engineering: These mechanisms allow multiple links to be used instead of concentrating traffic on one exit.
Advanced services: BGP address-family extensions support IPv6, MPLS VPNs, multicast, and EVPN.
Common Path Attributes
Attribute
Classification
Purpose
AS_PATH
Well-known mandatory
Lists traversed ASes; supports loop detection and path-length comparison
NEXT_HOP
Well-known mandatory
Gives the address of the next-hop router
LOCAL_PREF
Well-known discretionary
Higher values indicate preferred routes within an AS
MED
Optional non-transit
Lower values indicate preferred entry paths, normally among routes from the same neighboring AS
ORIGIN
Well-known mandatory
Identifies how the route was learned: IGP, EGP, or incomplete
COMMUNITIES
Optional transitive
Tags routes for policy actions such as NO_EXPORT
Trade-offs and Practical Guidance
Table growth: The global BGP table is large and continues to grow as operators advertise more specific prefixes. Route aggregation and filtering help control unnecessary growth.
Convergence: BGP is policy-driven rather than purely metric-driven. Withdrawal propagation and route selection can take longer than internal gateway protocol convergence.
Operational complexity: Incorrect filters, route leaks, or conflicting policies can create black holes or direct traffic through expensive transit providers.
Security: BGP does not inherently authenticate the origin of every route. Operators use prefix filters, maximum-prefix limits, session authentication, and RPKI origin validation. RPKI validates route origin, not the complete AS path.
Good practice: Monitor BGP sessions and table changes, document communities and policies, apply inbound and outbound filters, use route reflectors carefully, and test changes before deployment.
39
How do interior and exterior gateway protocols differ?
KnownRevise
Interior Gateway Protocols (IGPs) exchange routing information within a single autonomous system, while Exterior Gateway Protocols (EGPs) exchange routes and path attributes between autonomous systems. BGP is the protocol used for modern inter-domain routing, with path attributes allowing each autonomous system to apply policy.
Read full answerHide full answer
Applies toall versions of IPv4 and IPv6 routing, including BGP as specified by RFC 4271 and subsequent updates
Key Distinctions
Aspect
Interior Gateway Protocols
Exterior Gateway Protocols
Routing scope
Within one autonomous system
Primarily between different autonomous systems
Main objective
Build an internal map and select routes according to a topology metric
Advertise reachable networks while applying inter-domain policy
Common protocols
OSPF, IS-IS, RIP
BGP
Routing model
RIP is distance-vector; OSPF and IS-IS are link-state
BGP is a path-vector protocol
Path selection
Usually based on metrics such as hop count or link cost
Based on attributes such as local preference, AS path length, origin, and MED
Transport
RIP uses UDP port 520, OSPF uses IP protocol 89, and IS-IS runs directly over the data-link layer
BGP uses TCP port 179
Administrative focus
Efficiency and reachability inside the organization
Connectivity, policy, and avoiding unwanted route transit
How Interior Routing Works
An autonomous system (AS) is a collection of routers and IP prefixes operated under a common routing policy and identified by an ASN. An IGP allows routers in that AS to discover networks and choose internal paths.
RIP uses hop count as its metric. It is simple but unsuitable for large networks because its maximum valid path length is 15 hops.
OSPF builds a link-state database describing the topology. Each router runs the shortest-path-first algorithm to calculate routes.
IS-IS also uses a link-state model and is widely deployed by large service providers.
For example, a company may run OSPF between its office routers, data-center leaf routers, and core routers. The routers learn internal prefixes and select paths using OSPF costs.
How Exterior Routing Works
BGP allows routers in different autonomous systems to advertise IP prefixes and associated path attributes. It is primarily a policy protocol, not simply a shortest-path protocol.
eBGP exchanges routes between autonomous systems, usually through sessions between border routers.
iBGP exchanges BGP routes among BGP speakers inside the same AS.
An AS normally combines both: an IGP provides internal reachability, while BGP exchanges external routes through border routers.
For example, when an ISP advertises an assigned, globally routable public prefix to another provider using BGP, the receiving provider can accept or reject that advertisement according to commercial and technical policy. The prefix also carries attributes describing how the route was learned and traversed.
BGP and Historical EGP Terminology
The textbook term Exterior Gateway Protocol originally referred to the early EGP protocol, which allowed neighboring gateways to exchange routing information but did not support the complex policy and path-vector model required by the modern Internet.
That original protocol is obsolete. BGP, defined by RFC 4271 and updated by later RFCs, replaced it as the practical inter-domain routing protocol. Therefore, in current interviews, “EGP” is usually treated as the category represented by BGP, not as a recommendation to deploy the obsolete EGP protocol.
Trade-offs and Security
IGPs are generally simpler than BGP and can converge quickly within a controlled domain, but they trust the routers and topology information they receive. OSPF and IS-IS support authentication mechanisms that can reject updates from unauthenticated neighbors.
BGP offers flexible policy and large-scale scalability, but its routing table, session model, and configuration surface create substantial operational complexity. Common controls include:
Optional TCP MD5 authentication on supported deployments, although this does not encrypt BGP traffic
Prefix filtering, maximum-prefix limits, and explicit route policy
RPKI-based route-origin validation, with validators such as Routinator checking signed RIR delegation data
BGPsec where supported for cryptographic authentication of route origins and AS-path information
In real Linux and cloud networks, routes from multiple protocols may coexist in one routing table. The separation between “inside” and “outside” is therefore an administrative and architectural distinction rather than a strict separation of operating-system processes or routing software.
40
What is the transport layer's role in network communication?
KnownRevise
The transport layer provides process-to-process communication between applications on different hosts by delivering data across the network layer. TCP provides a reliable, ordered byte stream, while UDP provides lower-overhead, connectionless datagrams without built-in delivery guarantees.
Read full answerHide full answer
Applies toall versions of the OSI and TCP/IP models (TCP and UDP)
Core Role and Responsibilities
Process-to-process delivery: Uses port numbers to multiplex outgoing traffic and demultiplex incoming traffic to the appropriate application. TCP and UDP have separate port-number spaces.
Segmentation and message boundaries: TCP divides application data into segments and reconstructs a byte stream at the receiver. UDP preserves datagram boundaries, but it does not segment or reassemble application messages.
Connection management: TCP establishes a connection using a three-way handshake and closes it gracefully. UDP sends datagrams without a connection setup.
Reliability and ordering: TCP detects loss, retransmits missing data, and delivers bytes in order. UDP provides no guarantee of delivery, ordering, or uniqueness.
Flow control: TCP’s receiver advertises a window so the sender does not exceed the receiver’s available buffer capacity.
Congestion control: TCP adjusts its sending rate according to inferred network conditions. UDP itself provides no congestion-control mechanism.
Error detection: Both protocols use checksums. TCP combines this with acknowledgments and retransmission to recover missing or corrupted data; UDP typically discards datagrams that fail checksum validation but does not retransmit them.
TCP vs UDP
Feature
TCP
UDP
Service
Connection-oriented byte stream
Connectionless datagrams
Delivery
Reliable, ordered, and duplicate-free
Best effort; no delivery or ordering guarantee
Flow control
Receiver window
None in UDP itself
Congestion control
Built in
None in UDP itself
Header overhead
Minimum 20 bytes
Fixed 8 bytes
Common uses
HTTP/1.1 and HTTP/2, SMTP, FTP
DNS queries, RTP media, and application-designed protocols
TCP’s additional handshake, state, acknowledgments, and retransmissions increase overhead but simplify applications that require consistent delivery. UDP is useful when low latency, minimal protocol overhead, or application-specific control is more important.
How TCP Provides Reliability
TCP assigns byte sequence numbers and uses cumulative acknowledgments to indicate the next byte expected. If an acknowledgment is delayed or a duplicate acknowledgment indicates a gap, the sender retransmits the missing data. Its retransmission timeout is derived from measured round-trip time and its variation rather than being simply equal to one RTT.
TCP separates two forms of control:
Receiver flow control uses the advertised receive window to avoid overwhelming the destination.
Network congestion control limits the amount of unacknowledged data according to congestion conditions. Textbook algorithms commonly include slow start, congestion avoidance, and additive-increase/multiplicative-decrease behavior; modern systems may use algorithms such as CUBIC or BBR.
UDP instead sends each datagram independently. If an application needs reliability or ordering, it must implement the required behavior itself or use a protocol that does so over UDP.
Real-World Systems and Trade-offs
Operating systems such as Linux implement TCP and UDP in the kernel and expose them through sockets. Linux provides controls such as tcp_congestion_control for selecting the congestion-control algorithm, net.core.somaxconn for limiting the completed-connection queue, and net.ipv4.tcp_max_syn_backlog for limiting the SYN queue.
TCP can suffer from head-of-line blocking because later bytes in the same ordered stream cannot be delivered until missing earlier bytes are recovered. UDP does not impose stream ordering, although an application protocol layered over it may still do so. QUIC builds reliability, congestion control, stream multiplexing, and TLS 1.3 on UDP and is used by HTTP/3.
Neither TCP nor UDP provides encryption by itself. Traditional HTTPS uses TLS over TCP, while applications using QUIC or DTLS obtain encryption through those protocols.
Practical Guidance
Use TCP when correctness, ordered delivery, and straightforward application development matter.
Use UDP when the application needs minimal overhead or wants to implement its own reliability and congestion-control policy.
Do not assume that UDP is permanently “unreliable”: QUIC demonstrates how a protocol can add reliable, encrypted, multiplexed transport over UDP.
Remember that TCP is a byte stream. Applications requiring message boundaries must frame messages explicitly.
In practice, DNS normally uses UDP but can fall back to TCP, while modern web traffic may use TCP for HTTP/1.1 and HTTP/2 or QUIC over UDP for HTTP/3.
41
TCP vs UDP: differences and use cases
KnownRevise
TCP and UDP are the most widely used transport-layer protocols in the TCP/IP suite. TCP provides a connection-oriented, reliable, ordered byte stream, whereas UDP provides a connectionless, best-effort datagram service; the choice determines where reliability, ordering, flow control, and congestion control are implemented.
Read full answerHide full answer
Applies toTCP (RFC 9293), UDP (RFC 768), IPv4 (RFC 791), IPv6 (RFC 8200), and upstream Linux 6.x TCP
Key Differences
Feature
TCP
UDP
Connection
Connection-oriented; uses a three-way handshake
Connectionless; no transport-level setup
Reliability
Detects loss and retransmits data, providing ordered delivery while the connection remains usable
No guarantee of delivery; the application must tolerate loss
Data model
Byte stream without preserved message boundaries
Datagrams with preserved message boundaries
Ordering
Sequence numbers ensure in-order delivery
No ordering guarantee
Flow control
Receiver advertises a window limiting outstanding data
None
Congestion control
Built in; implementation and algorithm vary by stack
None in UDP itself
Header overhead
Minimum 20 bytes; options can increase it
Fixed 8 bytes
Processing and latency
Additional setup and recovery can increase delay
Less protocol overhead and no handshake, but latency is not inherently lower
Checksum
Required over IPv4 and IPv6
Optional in IPv4; mandatory in IPv6 except for specified tunneling cases
Packetization
Sender segments data according to the negotiated MSS and path MTU; 1460-byte MSS is common over IPv4 with a 1500-byte MTU
No MSS; a datagram is not inherently capped at the path MTU, although 1472 bytes is a common UDP/IPv4 payload with that MTU
How TCP Works
Connection establishment: The client sends SYN, the server replies with SYN-ACK, and the client sends ACK. This establishes connection state and synchronizes the initial sequence numbers.
Data transfer: TCP numbers bytes in a sequence space. A cumulative ACK identifies the next byte expected; duplicate acknowledgments or a retransmission timeout can cause missing data to be retransmitted.
Flow control: The receiver advertises a window representing how much data it is currently willing to accept. The sender must not exceed that limit, protecting the receiver’s buffer.
Congestion control: TCP uses network signals such as loss and delay to manage its sending rate. Algorithms include slow start, congestion avoidance, and fast recovery; upstream Linux 6.x uses CUBIC (RFC 8312) by default.
Connection teardown: Each direction is closed independently, normally using a four-segment FIN/ACK exchange.
How UDP Works
Each datagram contains source and destination ports, a length, and a checksum in an 8-byte header.
The UDP transport maintains no connection state. Datagrams are handled independently, and their message boundaries are preserved.
UDP has no handshake, retransmission, ordering, flow control, or congestion control, so it avoids transport-level setup and loss-recovery delay.
IPv4 permits a zero UDP checksum, although modern applications normally calculate it. IPv6 normally requires a valid UDP checksum.
IP fragmentation rules still apply. IPv4 routers or the source may fragment an oversized datagram; with IPv6, the source—not a router—must fragment it or use path-MTU discovery.
Use Cases
TCP is preferred when: - Complete and correctly ordered delivery is required, such as file transfer, SMTP, or SSH. - The application uses a byte-stream protocol, including HTTP/1.1 and HTTP/2 over TCP, FTP, and TLS over TCP. - The application can tolerate retransmission-induced delay and does not have strict per-message latency requirements.
UDP is preferred when: - Low latency matters and the application can recover from loss itself, as with RTP-based voice and video, some real-time games, and telemetry. - Broadcast or multicast is required; UDP supports both, while TCP does not natively support multicast. - Conventional DNS can use UDP for typical queries, with TCP used for zone transfers and other large responses. - A protocol supplies its own reliability and congestion control, notably HTTP/3 through QUIC over UDP.
Trade-offs and Best Practices
Reliability versus latency: TCP retransmits missing data, which may delay later bytes; UDP avoids that delay but can lose data. A single TCP byte stream also has head-of-line blocking, although modern multipath and QUIC-based systems can mitigate some forms of it.
Application complexity: TCP supplies reliability and congestion control. UDP gives the application more control but requires it to implement any required recovery, ordering, pacing, and congestion-control mechanisms.
Congestion: UDP without congestion control can send faster than the network can carry, causing queueing and loss. Applications should pace their traffic or use a congestion-controlled transport such as QUIC.
Security: Neither TCP nor UDP provides encryption or peer authentication, and their checksums detect accidental corruption rather than malicious modification. Use TLS with TCP, DTLS with UDP, or an appropriate application-level security mechanism.
Common pitfall: Do not assume UDP is automatically faster or TCP is automatically appropriate. Base the decision on delivery requirements, latency sensitivity, multicast needs, message boundaries, and the security mechanism required.
Modern HTTP: HTTP/3 uses QUIC over UDP. QUIC provides reliable multiplexed streams and integrates a mandatory TLS 1.3 handshake, avoiding the connection-wide head-of-line blocking of HTTP/2’s single TCP byte stream.
42
How does the TCP three-way handshake establish a connection?
KnownRevise
The TCP three-way handshake is the sequence of three TCP segments used to initialize a connection, synchronize sequence numbers, and negotiate connection parameters. It confirms basic reachability in both directions, but it does not authenticate either endpoint.
Read full answerHide full answer
Applies tocomputer networks (TCP/IP; all standard versions of TCP)
Handshake Exchange
Assume a client connects to a web server at 192.0.2.10:443 from TCP port 52000:
Step
Sender
TCP flags
Sequence information
1
Client → Server
SYN
Client selects an Initial Sequence Number, such as 1000
2
Server → Client
SYN, ACK
Server selects an Initial Sequence Number, such as 5000; acknowledges 1001
3
Client → Server
ACK
Client acknowledges 5001; the connection becomes established
In the first segment, the client sets the SYN flag and sends its Initial Sequence Number (ISN). The SYN consumes one sequence number, so the server acknowledges the next expected sequence number, client_ISN + 1.
The server responds with SYN and ACK set. Its ACK field confirms the client’s sequence space, while its own ISN begins the server’s sequence space.
The client then sends an ACK containing server_ISN + 1. This segment normally carries no application payload. After it is processed, the TCP connection is established and both sides can exchange application data.
Connection State Changes
The standard TCP state machine models the handshake as follows:
Client:CLOSED → SYN-SENT → ESTABLISHED
Server:LISTEN → SYN-RECEIVED → ESTABLISHED
These states describe protocol progress, not necessarily the exact names shown by every operating system. Linux, for example, may use kernel optimizations such as SYN cookies while retaining the same TCP sequence-number exchange.
Negotiated Options
The handshake also allows the endpoints to advertise TCP options:
Maximum Segment Size (MSS): The largest TCP payload the sender is willing to receive.
Window Scale: Multiplies the receive-window field for high-bandwidth connections.
SACK permitted: Allows selective acknowledgment of received segments.
Timestamps: Help estimate round-trip time and detect stale segments more accurately.
MSS is commonly determined from the maximum IP packet size minus the IP and TCP headers. For Ethernet with a 1500-byte MTU, the usual IPv4 MSS is approximately 1460 bytes.
Why Three Segments Are Required
A single acknowledgment cannot establish the connection because the client must learn the server’s sequence number, while the server must learn the client’s sequence number and receive confirmation that its own number was accepted.
Two segments are therefore insufficient: the first SYN only initiates communication, and the SYN-ACK still needs acknowledgment from the client. The third segment completes the exchange.
In practice, a capture may not show exactly three clean packets:
Lost segments cause retransmitted SYN or SYN-ACK packets.
A proxy or load balancer that terminates TCP runs a separate handshake with each side, so each capture point sees its own exchange.
Separately, TCP Fast Open does not add packets: it lets a returning client carry application data in the SYN (using a cookie from an earlier connection), so the server can respond with data in or right after the SYN-ACK, saving one round trip.
Security and Practical Considerations
The handshake provides basic reachability, not identity or authorization. Either endpoint can send a valid TCP segment; applications must use mechanisms such as TLS server certificates or mutual TLS when peer authentication is required.
A SYN flood sends many SYN segments without completing the handshake, potentially exhausting server resources. Defenses include SYN cookies, SYN queues, rate limiting, and upstream filtering.
When diagnosing a connection, sudo tcpdump -nn -i any 'tcp port 443' can show the flags and sequence numbers. Normal output generally shows Flags [S], then Flags [S.], then Flags [.]; retransmissions may indicate packet loss, congestion, or an incorrect path. ss and nstat can additionally show TCP states and retransmission counters.
Best Practices
Treat the handshake as connection establishment, not authentication.
Use TLS when confidentiality, integrity, or server authentication is required.
Monitor retransmissions and unusual numbers of SYN-RECEIVED connections.
Avoid assuming exactly three packets will appear in every packet capture.
Remember that SYN, SYN-ACK, and ACK are protocol flags; modern handshake packets may also carry TCP options.
43
How does TCP terminate a connection and enter TIME_WAIT?
KnownRevise
A TCP connection is normally terminated through a graceful FIN/ACK exchange, allowing each direction to close independently. The endpoint that actively closes enters TIME_WAIT for 2MSL, ensuring the final acknowledgment can be retransmitted and preventing delayed duplicates from an earlier connection affecting a later connection using the same four-tuple.
Read full answerHide full answer
Applies toTCP as specified in RFC 9293; common Linux and BSD TCP/IP stacks
Graceful Connection Termination
TCP is full-duplex, so closing one direction does not immediately terminate the entire connection. A FIN indicates that the sender will send no more data, but the peer may continue sending in the opposite direction until it also closes.
A typical client-initiated shutdown uses four segments:
The client sends FIN, entering FIN_WAIT_1.
The server acknowledges it with ACK and enters CLOSE_WAIT.
The server application finishes and sends its own FIN, moving the server to LAST_ACK.
The client acknowledges that FIN and enters TIME_WAIT.
The client moves from TIME_WAIT to CLOSED after the TIME_WAIT timer expires.
Event
Active closer
Passive closer
Sends FIN
FIN_WAIT_1
CLOSE_WAIT after receiving FIN
Receives acknowledgment
FIN_WAIT_2
CLOSE_WAIT
Sends final FIN
FIN_WAIT_2
LAST_ACK
Receives final acknowledgment
TIME_WAIT
CLOSED
TIME_WAIT expires
CLOSED
Already closed
An abrupt termination may instead use a RST, which discards the connection state without a graceful shutdown. This is appropriate for errors or applications that do not need to exchange remaining data.
Why TIME_WAIT Exists
TIME_WAIT is entered by the endpoint that performs the active close. It is not a state where normal application data is processed; it temporarily preserves the minimum connection information needed to handle retransmissions safely.
The endpoint waits for 2MSL, where MSL means “maximum segment lifetime.” This provides two protections:
Final acknowledgment recovery: The final ACK could be lost. If the peer retransmits its FIN, the TIME_WAIT endpoint can retransmit the ACK.
Protection against old duplicates: TCP delayed segments or duplicates from the previous connection might arrive after the same source address, destination address, source port, and destination port are reused. Waiting prevents these segments from being accepted by a new connection.
The exact MSL and effective TIME_WAIT duration depend on the operating system and configuration; a common modern duration is about 60 seconds, but it should not be treated as a universal value.
TIME_WAIT in Real Systems
Many TIME_WAIT sockets are normal, especially when clients or servers create many short-lived connections. They are more likely to cause operational problems when:
A client consumes many ephemeral local ports.
A server actively closes many accepted connections, retaining the server-side local port in TIME_WAIT.
A process opens and closes connections faster than TIME_WAIT entries can expire.
Connection pooling, HTTP keep-alive, graceful application shutdown, and correct load-balancer draining reduce this pressure. On Linux, TIME_WAIT sockets can be inspected with:
ss -tan state time-wait
Common Pitfalls
TIME_WAIT is not necessarily a leak: It is part of TCP’s duplicate and retransmission protection.
FIN is half-close, not an immediate full close: The receiving application must close its sending direction separately.
Do not disable TIME_WAIT casually: Forcing connections closed faster without understanding duplicate-segment risks can corrupt a later connection.
SO_REUSEADDR is not a complete solution: It affects address-binding rules but does not remove TCP’s fundamental sequence and duplicate-segment protections.
44
How does TCP provide reliable byte-stream delivery?
KnownRevise
TCP provides reliable, ordered delivery by combining sequence numbers, acknowledgments, checksums, retransmissions, flow control, and congestion control. It retransmits unacknowledged data and suppresses duplicates at the receiver, providing a reliable byte stream rather than preserving application message boundaries; delivery remains conditional on the connection not failing irrecoverably.
Read full answerHide full answer
Applies tocomputer networks (TCP over IPv4 and IPv6, including RFC 9293)
Core Reliability Mechanisms
TCP maintains a Transmission Control Block (TCB) for each connection. It tracks sequence numbers, acknowledged data, retransmission timers, the receiver’s advertised window, and congestion-control state.
Mechanism
Purpose
Sequence numbers
Identify every byte in the TCP stream and allow duplicate or reordered segments to be detected
Acknowledgments
Confirm which bytes the receiver has accepted; an ACK normally identifies the next byte expected
Checksum
Detect corruption caused by transmission errors
Retransmission
Resend data that is not acknowledged or is suspected of being lost
Receiver buffering
Hold out-of-order segments until the missing bytes arrive
Sliding window
Allow multiple segments to be in flight without waiting for an ACK after every segment
Flow control
Prevent the sender from overwhelming the receiver
Congestion control
Prevent the sender from overwhelming the network
The sender keeps unacknowledged data until it receives an acknowledgment. If an acknowledgment is delayed or lost, a retransmission timer eventually causes the relevant segment to be sent again.
Ordering and Duplicate Handling
TCP numbers bytes rather than individual application messages. For example, a segment carrying bytes 1000–1499 may be followed by one carrying bytes 1500–1999.
If the second segment arrives first, the receiver buffers it and acknowledges byte 1500, meaning that bytes before 1500 are still missing.
If the first segment later arrives, the receiver delivers bytes 1000–1499, then releases the buffered bytes.
If the sender later retransmits bytes 1000–1499, the receiver recognizes the duplicate and does not deliver those bytes again.
This produces a reliable byte stream, but not reliable message delivery. If an application writes two separate messages, TCP may combine them, split them across segments, or deliver them together.
Loss Detection and Retransmission
TCP detects loss using two primary signals:
Timeout: A retransmission timeout, calculated from measured round-trip time and its variation, indicates that an acknowledgment has not arrived soon enough.
Fast retransmit: Several duplicate acknowledgments indicate that later data arrived while an earlier segment was missing. TCP can retransmit the suspected segment before waiting for the timeout.
Selective Acknowledgment (SACK) can also identify ranges of received data, allowing the sender to retransmit only missing portions. This is an optional TCP extension and is commonly supported by modern operating systems.
Checksums detect corrupted segments, but they do not themselves recover lost data; retransmission provides recovery.
Flow Control and Congestion Control
These mechanisms solve different problems:
Flow control protects the receiver. The receiver advertises a window indicating how much additional data it can buffer. The sender must not have more unacknowledged data than that window permits.
Congestion control protects the network. The sender maintains a congestion window based on feedback such as packet loss or explicit congestion notification. It adjusts how much data may be sent according to algorithms such as slow start, congestion avoidance, and fast recovery.
TCP may reduce its sending rate when it detects congestion or receiver pressure. Consequently, retransmission can improve reliability at the cost of higher latency.
Connection Lifecycle and Practical Limitations
TCP normally establishes a connection with a three-way handshake and closes it gracefully with FIN exchanges. The three-way handshake synchronizes initial sequence numbers, while per-connection state and sequence-space checks prevent stale segments from an earlier incarnation of the same connection from being accepted. FIN exchanges request an orderly shutdown.
TCP has important trade-offs:
Head-of-line blocking: Missing earlier bytes prevent later bytes from being delivered to the application, even if later bytes have arrived.
Latency under loss: Retransmission delays delivery.
Connection state: Sequence numbers, timers, buffers, and control state must be maintained for every connection.
No absolute delivery guarantee: If the connection fails permanently, TCP reports the error rather than delivering data indefinitely.
In textbook models, reliability is presented as a direct sequence-and-acknowledgment process. Real systems such as Linux additionally use SACK, timestamps, window scaling, adaptive congestion-control algorithms, and hardware checksum or segmentation offload. UDP provides neither ordering nor automatic retransmission, so applications using UDP must implement any required reliability themselves.
45
How does the TCP receiver window control sender data flow?
KnownRevise
TCP flow control prevents a fast sender from overwhelming a slower receiver by limiting how much unacknowledged data the sender may transmit. The receiver advertises its available buffer space using the receiver window (rwnd), which the sender respects when deciding how much more data to send.
Read full answerHide full answer
Applies toTCP/IP networking and all standard TCP implementations
How TCP Flow Control Works
TCP flow control operates between the two endpoints of a connection, independently of congestion control:
The receiver maintains a receive buffer for incoming data.
The receiver application reads data from that buffer.
The receiver advertises the amount of space available in a TCP segment, normally with an ACK.
The sender limits outstanding data according to the advertised window.
As the application reads more data, the receiver advertises a larger window.
The advertised window indicates how far beyond the acknowledged sequence number the sender may transmit. A simplified view is:
available receive space = receive-buffer capacity - unread buffered data
The receiver does not merely advertise its total buffer size. A buffer that is already full causes the receiver to advertise a small window or a zero window.
The Receiver Window (rwnd)
rwnd is the sender’s estimate of how many bytes the receiver can currently accept. The effective amount the sender may place in flight is generally bounded by:
send limit = min(rwnd, cwnd)
Here, cwnd is the congestion window, controlled by the sender’s congestion-control algorithm. rwnd protects the receiver; cwnd protects the network.
The TCP header contains a 16-bit window field. TCP window scaling, negotiated during the connection handshake, shifts this value so modern systems can advertise receive windows larger than 65,535 bytes. Without scaling, the largest representable window is 65,535 bytes.
Worked Example
Suppose a receiver has a 64 KiB receive buffer:
Total buffer capacity: 65,536 bytes
Data already read by the application: 20,480 bytes
The receiver therefore advertises rwnd = 49,152 bytes. If the sender’s congestion window is only 32 KiB, it can still have at most:
min(49,152, 32,768) = 32,768 bytes in flight
The receiver window is not restrictive in this case. If the application stops reading and the buffer fills, rwnd falls toward zero.
Zero-Window Handling
A receiver advertises a zero window when it cannot accept additional data, commonly because the application is slow or the buffer is full.
The sender must then stop sending normal data. It does not wait indefinitely because the receiver may later reopen the window. Instead, it periodically sends TCP zero-window probes to prompt a new window advertisement.
Potential causes include:
The receiving application is not reading from the socket.
The receive buffer is exhausted.
An intermediate proxy or traffic-control mechanism has throttled the connection.
On Linux, ss -tin can expose TCP window and congestion-control information for established sockets.
Receiver Window vs. Congestion Window
Mechanism
Controlled by
Protects against
Main signal
Receiver window (rwnd)
Receiver
Overrunning the receiver
Advertised available buffer space
Congestion window (cwnd)
Sender
Overloading the network
Congestion-control algorithm and feedback
Sender buffer
Sender/application
Insufficient local buffering
Operating-system socket configuration
A sender must not use the receiver window to infer that the network is uncongested. It must apply both limits. Real operating systems also combine these limits with local send-buffer capacity and application write behavior, so the actual number of bytes on the wire may be smaller than the calculated window.
Practical Considerations
Do not confuse buffering with consumption: the receiver can advertise space even if its application has not processed the data yet.
Window updates accompany ACKs: advertisements are normally communicated when the ACK advances or when the available window changes.
Delayed ACKs are not primarily flow control: they reduce packet overhead, while the window field independently controls data transmission.
Buffer sizing affects performance: an undersized receive buffer can cause frequent zero-window conditions, while an oversized buffer can allow one TCP connection to occupy substantial memory.
Intermediate devices may also throttle connections: network devices, proxies, and traffic shapers can restrict effective throughput independently of the endpoint’s rwnd.
46
TCP congestion control: slow start, congestion avoidance, fast recovery?
KnownRevise
TCP congestion control is the sender-side mechanism that limits data in flight so a TCP sender does not overload the network path. It adjusts the congestion window (cwnd) using loss signals, timeouts, or Explicit Congestion Notification (ECN), progressing through slow start, congestion avoidance, fast retransmit, and fast recovery in the classic TCP algorithm.
Read full answerHide full answer
Applies toTCP/IP congestion control under RFC 5681 and RFC 9438 (CUBIC), with RFC 6928 initial-window guidance; mainline Linux TCP with CUBIC as the upstream default
Core Concepts
Congestion window (cwnd): A sender-side limit on outstanding data. The sender cannot have more than approximately min(cwnd, rwnd) bytes in flight, where rwnd is the receiver’s advertised window.
Flight size: The amount of data sent but not yet acknowledged. It determines the congestion response when loss is detected.
Initial window (IW): RFC 6928 recommends IW = min(10*MSS, max(2*MSS, 14,600 bytes)). With a 1460-byte MSS, this is 10 MSS, or 14,600 bytes.
ACK clocking: Each ACK permits the sender to transmit additional data, so window growth is paced by the round-trip time rather than by a fixed timer.
Slow Start and Congestion Avoidance
Phase
Starting condition
Window growth
Transition
Slow start
New connection or timeout recovery
Approximately doubles per RTT
Continue until cwnd >= ssthresh
Congestion avoidance
cwnd >= ssthresh
Approximately increases by 1 MSS per RTT
Continue until a congestion event occurs
Slow start increases cwnd aggressively. For each ACK cumulatively acknowledging new data, the RFC 5681 increase is min(bytes_acknowledged, SMSS), producing approximately exponential growth.
Congestion avoidance uses the approximate rule cwnd += SMSS * bytes_acknowledged / cwnd, which yields roughly one additional MSS per RTT.
Worked example: With MSS = 1460 bytes, ssthresh = 40 MSS, and RTT = 40 ms, slow start grows cwnd from 10 to 20 to 40 MSS in two RTTs. At 40 MSS, the sending rate is approximately 58,400 / 0.04 = 1,460,000 bytes/s, or 1.46 MB/s.
Fast Retransmit and Fast Recovery
Fast retransmit: After three duplicate ACKs, TCP retransmits the apparently missing segment without waiting for the retransmission timeout. This behavior is specified by RFC 5681; RFC 6582 defines NewReno’s changes to fast recovery, and SACK itself is defined in RFC 2018.
On the third duplicate ACK, the classic RFC 5681 response is:
ssthresh = max(FlightSize / 2, 2*MSS)
cwnd = ssthresh + 3*MSS
Fast recovery keeps the window inflated while additional duplicate ACKs arrive, each increasing cwnd by approximately one MSS. This maintains throughput while repairing the loss.
When an ACK acknowledges new data, cwnd is reduced to ssthresh, and congestion avoidance resumes.
Worked example: If flight size is 40 MSS, ssthresh becomes 20 MSS and cwnd becomes 23 MSS during fast recovery. After recovery, cwnd returns to 20 MSS.
Timeout, ECN, and Algorithm Variants
Timeout: An RTO is a strong congestion signal. RFC 5681 reduces cwnd to the loss window of 1 MSS and restarts slow start; ssthresh is normally max(FlightSize / 2, 2*MSS). RFC 6298 specifies an initial RTO of at least one second and exponential backoff.
ECN: RFC 3168 allows routers to mark packets with the Congestion Experienced (CE) bit rather than dropping them. The sender reduces cwnd according to its congestion-control algorithm; the packet is not retransmitted merely because it was marked.
Variant
Main behavior
Status
Tahoe
Collapses to 1 MSS on timeout; does not use Reno-style fast-recovery inflation
Teaching baseline
Reno
Uses fast recovery after three duplicate ACKs and collapses on timeout
Classic textbook algorithm
NewReno
Improves recovery when multiple segments are lost in one window
Widely implemented
CUBIC
Uses cubic-time growth and a reduction factor of 0.7
RFC 9438; Linux upstream default
BBR
Estimates bottleneck bandwidth and propagation RTT rather than relying primarily on packet loss
Deployed alternative published as an IETF draft
Practical Takeaways and Trade-offs
Slow start finds usable path capacity quickly but can create a burst; congestion avoidance grows more cautiously but takes longer to use available bandwidth.
Fast recovery avoids the severe throughput collapse of a timeout, while a timeout remains necessary when duplicate ACKs are insufficient.
SACK improves retransmission efficiency, and TCP timestamps support RTT measurement and PAWS. Mild reordering is primarily tolerated through duplicate-ACK thresholds rather than SACK alone.
A receiver or application may be the bottleneck even when cwnd is small; bufferbloat requires active queue management such as CoDel or FQ-CoDel rather than only congestion-window changes.
In data centers, ECN-based mechanisms such as DCTCP or TCP Prague can react before packet loss.
Linux’s net.ipv4.tcp_slow_start_after_idle controls whether cwnd is reset after an idle period.
47
What is the difference between flow control and congestion control in networking?
KnownRevise
Flow control and congestion control are both essential mechanisms in computer networks, but they address different problems. Flow control matches the sender’s transmission rate to the receiver’s ability to process incoming data, preventing buffer overflow at the receiver. Congestion control adjusts the sending rate to avoid overwhelming the network infrastructure (routers and links), preventing congestion collapse.
Read full answerHide full answer
Applies tocomputer networks (TCP/IP and OSI models, transport layer)
How Flow Control Works
Purpose: Ensure the sender never transmits data faster than the receiver can consume it.
Mechanism: The receiver advertises its available buffer space (e.g., the window field in a TCP header). The sender limits the amount of unacknowledged data to this advertised window.
Example: If a receiver’s buffer fills, it advertises a zero window; the sender pauses transmission until the receiver frees space and sends a window update.
Layer: Typically implemented at the transport layer (e.g., TCP sliding window), though data-link protocols (such as Ethernet pause frames) also provide link-level flow control.
How Congestion Control Works
Purpose: Prevent the network from becoming overloaded by controlling the aggregate traffic sent by all active connections.
Mechanism: Senders detect congestion indirectly through packet loss, increased delay, or explicit signals (ECN). They then reduce their sending rate using algorithms like slow start, congestion avoidance, fast retransmit, and fast recovery.
Key state: Each TCP connection maintains a congestion window (cwnd) that limits the number of unacknowledged bytes. The effective window is the minimum of cwnd and the receiver’s advertised window.
Modern examples: Linux uses CUBIC by default; other variants include BBR and Reno. The algorithms dynamically adjust cwnd in response to ACKs and loss events.
Key Differences
Aspect
Flow Control
Congestion Control
What it regulates
Sender ↔ receiver rate
Sender ↔ network capacity
Primary signal
Receiver’s advertised window
Packet loss, delay, or ECN
Goal
Match sender speed to receiver processing speed
Match aggregate traffic to available link capacity
Who participates
Sender and receiver
Senders, routers, and network links
Typical implementation
TCP receiver window
TCP congestion window (cwnd)
Failure mode
Receiver buffer overflow
Network congestion collapse
Interaction in TCP
TCP combines both controls into a single limit: the sender may not have more than min(cwnd, receiver_window) bytes outstanding. When the network is congested, cwnd shrinks and dominates; when the receiver is slow, the receiver window dominates. This interaction ensures that neither the receiver nor the network is overloaded, but it also means that a slow receiver can artificially throttle the connection even if the network has ample capacity.
Practical Considerations
Flow control alone cannot prevent congestion—many flows each respecting receiver windows can still saturate a link.
Congestion control alone cannot prevent receiver buffer overflow if the receiver is slower than the network path.
Application-level backpressure (e.g., in message queues) is another form of flow control, independent of the transport layer.
Tuning congestion control parameters (e.g., cwnd growth, loss detection) involves trade-offs between throughput, latency, and fairness; the optimal choice depends on the network environment (data center vs. wide-area internet).
48
What are ports and sockets in computer networks?
KnownRevise
A port is a 16-bit transport-layer identifier used to direct traffic to an endpoint on a host, while a socket is the operating-system abstraction for a network communication endpoint. A socket represents communication context—such as a protocol, addresses, ports, and connection state—through which processes send and receive data.
Read full answerHide full answer
Applies toall versions of TCP/IP and general operating-system socket concepts
Port vs. Socket
Term
Meaning
Example
Port number
A 16-bit integer used to direct traffic to a particular transport-layer service on a host
TCP port 443
IP address
Identifies a network interface or host on an IP network
93.184.216.34
Socket
A software endpoint managed by the OS network stack
A TCP socket using 93.184.216.34:443
Socket API
The programming interface used to create and operate sockets
socket(), bind(), listen(), and accept() in POSIX
A destination endpoint is normally represented by the transport protocol, IP address, and port number. TCP and UDP maintain separate port spaces, so TCP port 8080 and UDP port 8080 can be used simultaneously without conflict.
Port Number Ranges
Ports are unsigned 16-bit values from 0 through 65535.
System or well-known ports (0–1023): Commonly associated with standard services, such as FTP on 21, SSH on 22, and SMTP on 25. Privileged access may be required to bind them on Unix-like systems.
Registered or user ports (1024–49151): Include commonly used service ports such as HTTPS on 443 and MySQL on 3306.
Dynamic or ephemeral ports (49152–65535): Commonly selected by the OS for temporary client connections, including outgoing TCP connections.
A client normally connects to a server’s well-known or registered port. The client’s OS then assigns an ephemeral source port so responses can be matched to the correct connection.
How Sockets Work
In the textbook TCP/IP model, an application asks the operating system to create a socket, bind it to a local address and port, and then use it for communication.
For a typical TCP server:
The server creates a TCP socket.
It binds the socket to a local IP address and listening port.
It calls listen() to mark the socket as a listening socket.
An incoming connection causes accept() to return a new connected socket.
The server exchanges application data through the connected socket.
The socket is closed when communication ends.
A connected TCP socket is commonly identified by the five-tuple:
protocol, source IP, source port, destination IP, destination port
This allows many clients to connect to the same server address and port concurrently. The listening socket and accepted sockets are distinct OS objects: the listening socket accepts new connections, while each connected socket represents one TCP conversation.
For UDP, there is no connection handshake. A server normally binds a UDP socket to a local port and receives independent datagrams. A UDP socket may be connected at the API level, but UDP itself is connectionless and provides no TCP-style handshake, ordered delivery, or retransmission.
Concrete Example
Suppose a browser requests a website from 93.184.216.34 over HTTPS:
Destination address: 93.184.216.34
Destination port: 443
Source address: the client’s local IP address
Source port: an ephemeral port assigned by the client OS, such as 51234
The TCP connection is therefore identified by:
TCP, 192.168.1.25, 51234, 93.184.216.34, 443
The server-side HTTPS process normally listens on port 443. The TCP connection is established before the browser sends the HTTP request, and TLS then negotiates encryption over that TCP connection.
Inspecting Ports and Sockets
On Linux, ss -ltnp shows listening TCP sockets and their owning processes, while ss -uanp shows UDP sockets and their owning processes.
A listening HTTPS server might appear with an address such as 0.0.0.0:443 or [::]:443. The first listens on all IPv4 interfaces; the second listens on all IPv6 interfaces, depending on the server’s socket configuration. 127.0.0.1:8080 accepts connections only through the IPv4 loopback interface.
Common Misunderstands and Trade-offs
A port is not a unique identifier for a process; ownership, permissions, and binding behavior are controlled by the OS.
A port number alone does not identify a remote service across the Internet; the IP address and transport protocol are also required.
“Sockets” can refer either to the conceptual communication endpoint or to the kernel-managed OS resource exposed as a file descriptor on Unix-like systems.
Firewalls and security groups may block a port even when an application is listening on it.
The port-range conventions are managed by IANA, but operating systems and local policies can vary in how ports are reserved or restricted.
TCP versus UDP sockets: TCP sockets provide ordered, reliable byte streams and connection state at the cost of a handshake and per-connection overhead. UDP sockets provide low-overhead datagrams without built-in guarantees for delivery, ordering, or retransmission.
49
How does QUIC mitigate transport-layer head-of-line blocking?
KnownRevise
Head-of-line blocking (HOL blocking) occurs when missing data prevents later data from being delivered, even though that later data has already arrived. QUIC mitigates this by providing independently ordered, multiplexed streams over UDP, so a gap in one stream does not stop delivery on other streams.
Read full answerHide full answer
Applies tocomputer networks (TCP/IP, QUIC v1 per RFC 9000, HTTP/3 per RFC 9114)
Meaning of Head-of-Line Blocking
In networking, HOL blocking is a delivery-order problem:
Data arrives or is acknowledged out of order.
The receiver cannot expose the later data because an earlier item is missing.
Processing therefore waits at the “head” of the sequence.
The concept appears at different layers. For example, if a router output queue is full, packets waiting behind a blocked packet may be delayed even when other output links are available. The question primarily concerns transport-layer HOL blocking in TCP.
Why TCP Suffers from It
TCP provides one reliable, ordered byte stream for a connection. Its receiver must deliver bytes to the application in sequence.
Suppose these TCP segments arrive:
Segment
Data range
Status
1
Bytes 1000–1499
Missing
2
Bytes 1500–1999
Received
Even though segment 2 has arrived, the application cannot receive its bytes until segment 1 is retransmitted and the gap is filled. Later bytes remain in the receive buffer.
This also affects multiplexed HTTP/2 requests because every HTTP/2 stream shares one TCP connection. Linux TCP optimizations such as Selective Acknowledgment (SACK) improve retransmission efficiency, but they do not remove the requirement that the application receive one byte stream in order.
How QUIC Mitigates It
QUIC, used by HTTP/3, runs over UDP and represents application data using multiple independent QUIC streams.
Each stream:
Has its own byte offsets and ordering rules.
Can be opened without blocking other streams.
Can deliver contiguous data independently of gaps in other streams.
Can have missing frames retransmitted without waiting for unrelated stream data.
Property
TCP
QUIC
Data organization
One ordered byte stream per connection
Multiple independently ordered streams
Effect of a gap
Blocks later data on the entire connection
Blocks only the affected stream’s delivery
Multiplexing
HTTP/2 streams share TCP ordering
HTTP/3 requests use separate QUIC streams
Congestion control
Connection-wide
Connection-wide
Loss recovery
Ordered byte-stream retransmission
Stream-aware frame and packet recovery
QUIC also uses separate packet number spaces for different connection aspects, preventing acknowledgment activity in one space from unnecessarily delaying another.
Concrete Example
A client downloads a page containing a large image and a small API response:
With HTTP/2 over TCP, loss of a TCP segment can prevent both the image and API response from being delivered because they share the TCP byte stream.
With HTTP/3 over QUIC, the API response can be delivered while the image stream still has a gap.
If the image and response frames were carried in the same lost QUIC packet, both would initially be affected. Nevertheless, the receiver need not withhold complete later data from unaffected streams.
Limitations and Real-World Behavior
QUIC does not eliminate every source of delay:
A gap still blocks later bytes within the same QUIC stream.
Congestion control is connection-wide, so loss can reduce the congestion window and slow all streams.
Server processing can still serialize requests if the application itself uses sequential logic.
QUIC depends on UDP support and suitable path validation; networks that block or rate-limit UDP can cause fallback or connection failure.
Thus, QUIC removes the TCP-specific coupling where one missing byte stalls every multiplexed response. It does not remove packet loss, congestion, application serialization, or head-of-line blocking within an individual ordered stream.
50
What functions does the application layer perform in networking?
KnownRevise
The application layer provides network services directly to user-facing applications, such as web browsers, email clients, and name resolvers. It defines application-specific communication rules rather than moving raw bits across a physical link.
Read full answerHide full answer
Applies tocomputer networks (OSI Layer 7 and the TCP/IP application layer)
How It Works
The application layer establishes meaning for communication between applications. Its protocols define:
Request and response formats: What messages look apart and how they are encoded.
Operations: Which actions are supported, such as retrieving an HTTP resource or resolving a DNS name.
Status and error handling: How success, redirection, authentication, and failure are reported.
Session semantics: Whether communication is stateful, stateless, persistent, or connection-oriented.
Resource access rules: How users and applications discover and use remote services.
The application layer normally relies on lower layers for addressing, routing, reliable delivery, flow control, and congestion control. For example, HTTP defines the meaning of a request and response, while TCP or QUIC provides the mechanism used to carry them.
Common Application-Layer Protocols
Protocol
Purpose
Typical transport
HTTP
Transfers web resources and application data
TCP for HTTP/1.1 and HTTP/2; QUIC over UDP for HTTP/3
DNS
Resolves domain names into IP addresses or other records
UDP and TCP
DHCP
Dynamically assigns network configuration such as IP addresses
UDP
SMTP
Supports sending and relaying email
TCP
IMAP
Retrieves and manages email on a server
TCP
FTP
Transfers files between hosts
TCP
NFS
Provides remote access to shared file-system resources
Usually TCP
TLS
Encrypts and authenticates application communication
Usually TCP; QUIC encrypts at the transport protocol level
In the OSI model, this is Layer 7. In the TCP/IP model, it is commonly called the application layer. TLS is sometimes described as OSI presentation or session functionality, but TCP/IP documentation generally treats it as an application-layer protocol.
Worked Example: Loading a Web Page
When a browser loads https://example.com/index.html, the application-layer activity typically includes:
DNS resolution: The browser asks a DNS resolver for the IP address of example.com.
Connection establishment: For HTTP/1.1 or HTTP/2, the client establishes a TCP connection and then performs a TLS handshake.
HTTP exchange: The browser sends an HTTP request containing the method, path, headers, and optional body.
Response processing: The server returns an HTTP response containing a status code, headers, and the requested content.
Content interpretation: The browser renders HTML, requests embedded resources, and executes application-layer web APIs as needed.
For HTTP/3, DNS and a QUIC handshake are followed by HTTP/3 requests over QUIC, which runs over UDP and provides its own reliability and congestion-control mechanisms.
Role Boundaries and Trade-offs
The application layer does not itself define:
IP addressing and routing: These belong to the network layer.
Ports, segmentation, and reliable delivery: These are transport-layer responsibilities.
Ethernet frames or wireless transmission: These belong to the data link and physical layers.
Some protocols trade simplicity for stronger guarantees. DNS normally uses UDP because small queries should be fast, but it can use TCP for large responses or certain zone transfers. HTTP/1.1 and HTTP/2 commonly use TCP for reliable ordered delivery, while HTTP/3 uses QUIC to avoid TCP’s head-of-line blocking across independent streams.
Real-System Considerations and Pitfalls
In Linux, application protocols are usually implemented in user space, while the kernel implements TCP/IP transport and network functions.
TLS may terminate in the application, a reverse proxy, or a load balancer, so the application may receive decrypted data even when clients use HTTPS.
Port numbers identify transport endpoints; the application-layer protocol defines the meaning of the messages exchanged through them.
Developers should not assume that a successful application response proves the entire path is secure. For example, HTTPS protects the connection but does not make the server’s content correct or the remote system trustworthy.
51
How does DNS resolve domain names to IP addresses?
KnownRevise
DNS resolves a domain name by querying a hierarchical, distributed system of name servers. The resolution may involve the client’s local resolver, cached answers, root servers, top-level domain servers, and the requested domain’s authoritative name server.
Read full answerHide full answer
Applies tocurrent DNS specifications for IPv4 and IPv6, including traditional DNS, DNS over TLS, and DNS over HTTPS
Resolution Process
Client requests a lookup An application calls a system resolver, commonly through getaddrinfo(), to resolve a name such as www.example.com. The client may first consult local sources such as /etc/hosts, depending on the operating system’s name-service configuration.
Recursive resolver checks its cache The system is usually configured with a recursive DNS resolver, operated by an ISP, organization, or public service such as Cloudflare DNS or Google Public DNS. The resolver checks cached records and their remaining time-to-live (TTL) values.
Root server provides a referral If the answer is not cached, the resolver asks a root name server. The root server normally does not return the final IP address. It directs the resolver to the appropriate top-level domain (TLD) server, such as the .com name server.
TLD server provides another referral The .com server refers the resolver to an authoritative name server responsible for example.com. This process is called iterative resolution: each server provides either an answer or a referral to a server closer to the authoritative data.
Authoritative server returns the answer The authoritative server returns the requested record, commonly:
A: an IPv4 address
AAAA: an IPv6 address
CNAME: an alias that must be resolved further
MX, TXT, NS, and other records for mail routing, verification, delegation, and configuration
Resolver returns and caches the result The recursive resolver sends the IP address to the client and caches the response according to its TTL. Other clients receiving the same query may be answered directly from this cache.
Worked Example
For www.example.com, the application sends a query to its configured recursive resolver. If no usable cached answer exists, the resolver asks a root server, follows the referral to a .com TLD server, and then follows that referral to the authoritative server for example.com. The authoritative server returns the relevant A or AAAA record, and the recursive resolver returns the address to the application.
The dig www.example.com A command requests the IPv4 record type, while dig www.example.com AAAA requests the IPv6 record type. By default, dig shows the answer and the recursive resolver that handled the query; dig +trace can be used to inspect the iterative delegation path.
If www.example.com is a CNAME pointing to host.example.net, the resolver may need additional queries to obtain the final address. The CNAME chain must also be followed before an A or AAAA answer is available.
Caching and Performance
Caching is DNS’s main performance mechanism:
Positive cache: Stores successful answers until their TTL expires.
Negative cache: Stores failures such as NXDOMAIN or NODATA according to the applicable negative TTL.
TTL: Controls how long records may remain cached. Lower TTLs allow faster changes but increase query traffic.
Cache locations: Recursive resolvers, forwarders, local stubs, and applications commonly cache DNS results; authoritative servers serve their zones’ data, while root and TLD servers generally provide referrals.
The textbook model uses a strict hierarchy. Real resolvers may also prefetch popular records, rotate among configured upstream resolvers, parallelize independent lookups, and apply local optimizations. Public resolvers can additionally answer from large shared caches.
Transport and Modern DNS
Traditional DNS uses port 53, usually over UDP for ordinary queries:
UDP is efficient because DNS messages are small and connectionless.
TCP is used when a response is truncated, for large responses, DNS zone transfers, and some other operations requiring reliable delivery.
DNS over TLS (DoT) encrypts DNS traffic over TCP port 853.
DNS over HTTPS (DoH) carries DNS inside HTTPS, commonly over TCP port 443; HTTP/3-based DoH can instead use QUIC over UDP port 443.
Encryption protects DNS query contents from passive observation but does not automatically make the returned address trustworthy.
Reliability and Security
DNS was not originally designed with strong authentication, so attackers may attempt DNS spoofing, cache poisoning, or redirection to malicious addresses. DNSSEC digitally signs DNS record sets and, with a valid chain of trust, allows validating resolvers to detect unauthorized changes and authenticate the data’s origin. It does not encrypt ordinary DNS traffic or prove that an IP address is safe.
Other protections include HTTPS/TLS for applications, source-port randomization, robust response validation, and monitoring unexpected DNS responses. DNS itself does not determine whether a destination is safe; it maps names to addresses and related DNS information.
52
What are DNS record types A, AAAA, CNAME, MX, TXT, NS?
KnownRevise
DNS record types define the mappings and routing information published in the Domain Name System. The most common records map names to IPv4 or IPv6 addresses, identify canonical names, route email, store text-based policies, and delegate authority for zones.
Read full answerHide full answer
Applies toDNS as defined in RFC 1034 and RFC 1035, with AAAA records from RFC 3596 and TXT-based policies such as SPF (RFC 7208)
Overview of DNS Resource Records
DNS is an application-layer protocol in the TCP/IP model and corresponds to the application layer in the OSI model. It is a hierarchical, distributed naming system in which authoritative name servers publish resource records (RRs).
A formal RR contains an owner name, type, class, TTL, and RDATA. Zone files commonly display this as owner [TTL] [class] type RDATA; the Internet primarily uses class IN. An RR set is a collection of RRs having the same owner name, type, and class.
Common DNS Record Types
Type
Purpose
Zone-file example
Typical use
A
Maps a name to an IPv4 address
example.com. A 192.0.2.1
IPv4 host addressing
AAAA
Maps a name to an IPv6 address
example.com. AAAA 2001:db8::1
IPv6 host addressing
CNAME
Makes one name an alias for a canonical DNS name
www.example.com. CNAME example.com.
Aliasing a service hostname
MX
Identifies mail exchangers and their priorities
example.com. MX 10 mail.example.com.
Email routing
TXT
Stores text interpreted by an application or policy
example.com. TXT "v=spf1 -all"
SPF, DKIM, DMARC, verification
NS
Identifies authoritative servers for a zone
example.com. NS ns1.example.com.
Zone delegation and authority
Details and Constraints
A: Its RDATA is a 32-bit IPv4 address. A name may have several A records; resolvers may rotate their order, but DNS does not guarantee even traffic distribution or backend health awareness.
AAAA: Its RDATA is a 128-bit IPv6 address and serves the same addressing role as A for IPv6. Dual-stack deployments commonly publish both A and AAAA records.
CNAME: Its RDATA is a domain name, not a literal IP address. The target may itself have a CNAME, causing a resolver to follow a chain. A CNAME cannot coexist at its owner name with ordinary data such as A, AAAA, or MX. Consequently, a literal CNAME cannot normally exist at a zone apex because the apex also contains SOA and NS records; providers offering apex aliases generally synthesize or flatten A/AAAA answers instead.
MX: Its RDATA contains a 16-bit preference and an exchanger hostname. Lower preference values are tried first. If a server cannot accept mail, the sender may try the next MX; queueing and retry behavior belong to the mail systems, not to the MX record itself.
TXT: It contains one or more text character-strings whose meaning is defined by the application. SPF policies normally appear at the protected domain, DKIM public keys at names such as selector._domainkey.example.com., and DMARC policies at _dmarc.example.com..
NS: It identifies servers authoritative for a zone. A parent zone normally publishes NS records for a delegated child zone and may also publish A/AAAA glue records. The delegated zone’s apex contains its own NS records and an SOA record.
How Resolution Uses These Records
For www.example.com, a recursive resolver normally:
Receives the client’s query and obtains a referral to the .com name servers from a root server.
Obtains a referral to the example.com authoritative servers from a .com server.
Queries those authoritative servers for the requested record.
Follows a CNAME chain if necessary and returns the relevant answer.
The resolver caches positive and negative responses according to their TTLs. Authoritative servers publish current data immediately, but recursive and local caches can continue serving an earlier answer until its TTL expires.
Querying Records with dig
dig is a common command-line DNS query tool:
dig example.com A
dig example.com AAAA
dig example.com CNAME
dig example.com MX
dig example.com TXT
dig example.com NS
When the requested data exists, its RR set normally appears in the ANSWER SECTION. A CNAME chain can contain additional records, while addresses associated with NS or MX targets may appear in the ADDITIONAL SECTION. An absent name can instead produce NXDOMAIN or an empty answer.
Practical Considerations and Trade-offs
TTL management: Lowering a TTL before a planned migration lets cached answers expire sooner; lowering it only when the change is made does not remove already cached data. Longer TTLs reduce repeated queries but prolong stale answers.
Address records: Multiple A or AAAA records provide an address pool and can improve availability, but DNS alone does not perform load balancing or health checks.
Aliases versus address records: CNAME avoids duplicating addresses, but it adds resolution dependencies and cannot share an owner name with ordinary records.
TXT size: Each character-string in a TXT record is limited to 255 octets. A long record can contain multiple character-strings within the same RR.
DNSSEC: DNSSEC authenticates signed DNS data and its origin; it does not encrypt DNS traffic or prevent all denial-of-service attacks.
53
How do recursive and iterative DNS queries differ?
KnownRevise
A recursive DNS query asks a DNS server to produce the final answer, while an iterative DNS query asks for the best answer currently available so the querier can continue querying other servers. In practice, stub resolvers usually send recursive queries to a recursive resolver, which then performs iterative queries across the DNS hierarchy.
Read full answerHide full answer
Applies toDNS (IPv4 and IPv6; all protocol versions)
Core Difference
Query type
What the queried server must do
Who continues the lookup?
Recursive
Return the requested final answer or an error
The queried server performs the remaining work
Iterative
Return an answer or a referral to a more authoritative server
The original querier sends subsequent queries
The distinction is based on who is responsible for following referrals, not on whether the response contains an answer. A server can support both modes, and the mode is requested using specific DNS flags.
How a Typical Lookup Works
Suppose a client resolves www.example.com:
The host’s stub resolver sends a recursive query to a recursive resolver.
The recursive resolver checks its cache.
If no answer is cached, it sends an iterative query to a root name server.
The root server returns a referral to an appropriate .com TLD name server.
The resolver queries that TLD server, which returns a referral to the authoritative server for example.com.
The resolver queries the authoritative server and receives the requested A or AAAA record.
The resolver caches the result according to the record’s TTL and returns the final answer to the client.
The root and TLD servers normally do not retrieve the final record themselves. They provide referrals that allow the recursive resolver to proceed closer to the authoritative source.
Relevant DNS Flags
RD — Recursion Desired: Set by the client to request recursive service.
RA — Recursion Available: Set by a server to indicate that it will provide recursive service for the requesting client.
AA — Authoritative Answer: Indicates that the response contains an authoritative answer for the queried name.
RCODE: Identifies the result, such as NOERROR, NXDOMAIN, or SERVFAIL.
For an iterative exchange, the queried server can return a referral rather than the final answer. For a recursive exchange, the server should return either the final answer or an appropriate error such as SERVFAIL.
Trade-offs
Recursive queries simplify clients because the stub resolver does not need to implement referral-following and caching logic. They also allow many clients to share one recursive resolver’s cache. However, they concentrate lookup work and availability dependencies in the recursive resolver.
Iterative queries distribute hierarchy traversal across the client and DNS infrastructure. Root and TLD servers can return local referrals instead of performing the entire lookup. However, the querier must handle referrals, multiple server failures, caching, and the eventual authoritative response.
In deployed DNS, recursive queries dominate the client-to-resolver interface, while iterative queries are commonly used between the recursive resolver and the authoritative DNS hierarchy.
Textbook Model Versus Real Systems
The textbook model separates clients, recursive resolvers, and authoritative servers cleanly. Real deployments are more nuanced:
A stub resolver in an operating system, browser, or library sends recursive queries to a configured recursive resolver.
Recursive resolvers such as systemd-resolved, Unbound, BIND, or cloud-provided DNS services perform the iterative hierarchy traversal.
Forwarding resolvers may recursively query another resolver on the client’s behalf.
Caching at resolvers, browsers, operating systems, and applications reduces both recursive and iterative queries.
CDNs may operate authoritative DNS for delegated zones or steer clients to nearby endpoints using DNS records.
DNSSEC authenticates DNS data but does not change the recursive-versus-iterative query model.
A practical consequence is that a failure can occur at different layers: the stub resolver may fail to reach its recursive resolver, the recursive resolver may fail to traverse the hierarchy, or the authoritative server may fail or return an incorrect record.
54
How does DHCP assign IP addresses to clients?
KnownRevise
Dynamic Host Configuration Protocol (DHCP) automatically provides clients with IP addresses and related network settings, such as the subnet mask, default gateway, DNS servers, and lease duration. In DHCPv4, the process is commonly summarized as DORA: Discover, Offer, Request, and Acknowledgment.
Read full answerHide full answer
Applies tocomputer networks (DHCPv4; DHCPv6 uses a different protocol)
DHCPv4 Address Assignment
A client that needs an address does not normally begin with a usable IP configuration. It starts with an address such as 0.0.0.0 and uses UDP port 68, while DHCP servers listen on UDP port 67.
Stage
Sender
Message
Purpose
Discover
Client
DHCPDISCOVER
Broadcasts a request for available DHCP servers
Offer
Server
DHCPOFFER
Proposes an address and configuration
Request
Client
DHCPREQUEST
Identifies the chosen offer and asks the server to lease it
Acknowledgment
Server
DHCPACK
Confirms the lease and supplies final settings
Most initial client messages are broadcast to 255.255.255.255. The client can send a DHCPDISCOVER containing its MAC address and requested options. A server checks its address pools and returns a DHCPOFFER containing a proposed yiaddr, subnet mask, lease time, and other options.
The client then broadcasts a DHCPREQUEST. This is important when multiple servers offer addresses: the client selects one offer and lets the other servers know that their offers were not accepted. The selected server completes the assignment with a DHCPACK.
Leases and Configuration Options
DHCP assigns a lease, not permanent ownership of an address. The lease includes:
IPv4 address: The address assigned to the client.
Subnet mask: Determines which addresses are local to the client’s subnet.
Default gateway: The router used for destinations outside the local subnet.
DNS servers: Used to translate domain names into IP addresses.
Lease duration: Defines how long the configuration remains valid.
Before expiration, the client normally renews the lease. If renewal fails, it may attempt to rebind with any available DHCP server. Reusing addresses through leases is more practical than permanently reserving one address for every possible device.
Example with a Router Between Client and Server
Suppose the server manages this pool:
Network: 192.168.1.0/24
Usable pool: 192.168.1.100–192.168.1.199
Default gateway: 192.168.1.1
DNS server: 192.168.1.53
Lease time: 24 hours
A client with MAC address 00:11:22:33:44:55 might receive:
IP address: 192.168.1.142
Subnet mask: 255.255.255.0
Default gateway: 192.168.1.1
DNS server: 192.168.1.53
Lease duration: 86,400 seconds
The client applies the mask and sees that 192.168.1.53 is on its local subnet, so it can communicate with it directly. A destination such as 8.8.8.8 is outside the subnet and is sent through 192.168.1.1.
Routers, Relays, and Real Systems
A DHCP server can serve clients on a remote subnet through a DHCP relay agent, usually implemented by a router. The relay receives the client’s broadcast, adds the giaddr field identifying the client’s network, and forwards the request to the server. The server sends the reply through the relay, which delivers it to the client.
The textbook model is the same DORA exchange, but real deployments add policy and redundancy:
Linux servers: ISC DHCP (dhcpd) and Kea DHCP are common server implementations.
Linux clients: systemd-networkd, NetworkManager, and dhclient can request leases.
Windows clients: The DHCP Client service obtains and renews configurations.
Large networks: Servers use failover, policies, reservations, and multiple subnets to improve availability.
DHCPv6 follows the same broad purpose but is not a simple variant of DHCPv4. It uses UDP ports 546 and 547, multicast communication, and mechanisms such as IA_NA; it also supports stateless configuration through DHCPv6 for DNS information.
Security and Operational Considerations
Traditional DHCPv4 does not authenticate the server or cryptographically protect messages. An attacker can therefore act as a rogue DHCP server or exhaust the address pool.
Common protections include:
DHCP snooping: Trusted switches track legitimate DHCP server traffic and block unauthorized offers.
Source and destination validation: Switches reject DHCP server messages arriving from untrusted ports.
802.1X or port security: Restrict which devices can use a network port.
Network segmentation: Separate server, user, guest, and untrusted traffic.
Address reservations: Reserve specific addresses for predictable hosts, although this is not a security mechanism by itself.
For troubleshooting, tcpdump can reveal the DORA exchange, while ip address, ip route, and ss show the configuration and active sockets on Linux. A missing DHCPACK commonly indicates client–server UDP connectivity, relay configuration, exhausted pools, or incorrect scope addressing.
55
How does HTTP Work, and Which Methods Are Common?
KnownRevise
HTTP (Hypertext Transfer Protocol) is an application-layer protocol for exchanging resources, such as HTML documents, JSON data, images, and files, between clients and servers. It uses a request-response model: the client sends a request, and the server returns a response containing a status code, headers, and optionally a body.
Read full answerHide full answer
Applies toHTTP/1.1, HTTP/2, and HTTP/3
How HTTP Works
A typical exchange begins when a client requests a URL such as https://api.example.com/users/42:
The client parses the URL into the scheme, hostname, port, path, and query parameters.
It resolves the hostname to an IP address using DNS.
It establishes a transport connection:
HTTP/1.1 and HTTP/2 normally use TCP.
HTTP/3 uses QUIC over UDP, with encryption integrated into the protocol.
For https URLs, the client establishes TLS before exchanging HTTP messages.
The client sends an HTTP request.
The server processes it and returns an HTTP response.
HTTP is stateless: each request is interpreted independently. Session state is usually maintained using cookies, tokens, or application-level identifiers.
Request and Response Structure
A simplified HTTP/1.1 request looks conceptually like this:
Request line: Method, target, and protocol version, such as GET /users/42 HTTP/1.1.
Request headers: Metadata such as Host, Accept, Authorization, User-Agent, and Content-Type.
Request body: Optional data, commonly used by POST and PATCH.
An HTTP/1.1 response contains:
Status line: A numeric status code and reason phrase.
Response headers: Metadata such as Content-Type, Content-Length, Cache-Control, and Set-Cookie.
Response body: Optional resource content.
HTTP/2 and HTTP/3 do not use request or status lines. They encode request and response information in binary frames, with the status code represented by the :status pseudo-header; they do not include a reason phrase.
Common status codes include 200 OK, 201 Created, 204 No Content, 304 Not Modified, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 429 Too Many Requests, and 500 Internal Server Error.
Common HTTP Methods
Method
Purpose
Body
Safety and idempotency
GET
Retrieves a resource
Usually none
Safe and idempotent
HEAD
Retrieves the same headers as GET, without a body
None
Safe and idempotent
POST
Creates a resource or submits data for processing
Usually yes
Not inherently idempotent
PUT
Replaces a resource entirely
Usually yes
Idempotent
PATCH
Partially updates a resource
Usually yes
Not inherently idempotent
DELETE
Removes a resource
Usually none
Idempotent
OPTIONS
Queries communication options or supported methods
Usually none
Safe and idempotent
CONNECT
Establishes a tunnel through an intermediary
Not an application body
Not safe or idempotent
TRACE
Echoes the received request for diagnostics
Diagnostic data
Safe and idempotent; rarely enabled
These semantics come from RFC 9110. In practice:
GET should not modify server state.
PUT should perform the same intended update when repeated.
PATCH may or may not be idempotent depending on the patch format and operation.
POST can create duplicates if a client retries after an ambiguous failure.
TRACE is commonly disabled because it can expose sensitive request headers.
HTTP Version Differences
Version
Transport and framing
Important characteristics
HTTP/1.1
TCP; text-based messages
Supports persistent connections, Content-Length, and chunked transfer encoding
HTTP/2
TCP; binary framing
Multiplexes streams over one connection and uses HPACK for header compression
HTTP/3
QUIC over UDP; binary framing
Provides independent streams and usually faster connection setup and loss recovery
The textbook application-layer view is similar across versions. Real clients and servers, however, often use HTTP/2 over TLS or HTTP/3 over QUIC. Browsers may also cache resources, preload connections, or use service workers, so one visible page can generate many HTTP exchanges.
Best Practices and Common Pitfalls
Use GET for reads, POST for creation or non-idempotent processing, PUT for complete replacement, and PATCH for partial modification.
Do not depend on the exact order of headers. Header names are case-insensitive, while header values may have protocol-specific ordering rules.
Do not confuse 401 Unauthorized with 403 Forbidden: 401 usually means valid credentials are required, while 403 means the server refuses access.
Use HTTPS in production. TLS protects confidentiality and integrity in transit and authenticates the server through certificates, but it does not make an insecure application secure.
Set correct Content-Type and Cache-Control headers. Use ETag or Last-Modified for conditional requests.
Make retries safe by using idempotent methods or an idempotency key for operations such as payment creation.
Avoid exposing credentials, session tokens, or personal data in URLs because URLs are commonly stored in browser history, logs, and intermediary records.
56
What are HTTP status codes, and what do their main classes mean?
KnownRevise
An HTTP status code is a three-digit code in an HTTP response that summarizes the outcome of a request. Its first digit groups responses into five classes, helping clients, intermediaries, caches, and monitoring systems decide how to handle the result.
Read full answerHide full answer
Applies toHTTP/1.1, HTTP/2, and HTTP/3
Format and Main Classes
In HTTP/1.1, the status code appears in a textual status line such as HTTP/1.1 200 OK. The reason phrase is intended for human readability, while the numeric code determines the response semantics. HTTP/2 and HTTP/3 carry the code in the :status pseudo-header within their binary framing rather than using an HTTP/1.1-style status line.
Class
Meaning
Examples
1xx
Interim response while processing continues
100 Continue
2xx
Request successfully received, understood, and handled
200 OK, 201 Created, 204 No Content
3xx
Redirection or cache validation
301 Moved Permanently, 304 Not Modified
4xx
Request cannot be fulfilled because of a client-side problem
400 Bad Request, 401 Unauthorized, 404 Not Found
5xx
Server failed to fulfill an apparently valid request
500 Internal Server Error, 503 Service Unavailable
These classes indicate high-level responsibility, not absolute guarantees. For example, an application may deliberately return 404 to conceal a protected resource, while a gateway may return 503 before the request reaches the origin.
Common Codes
Code
Meaning
200 OK
Request succeeded; the response usually contains the requested representation.
201 Created
A resource was created; a Location header may identify it.
202 Accepted
Processing was accepted but may not yet be complete.
204 No Content
Request succeeded and the response intentionally has no message body.
301 Moved Permanently
The resource has a new permanent URI.
302 Found
A temporary redirection is available.
303 See Other
Directs the user agent to another URI, typically using GET.
304 Not Modified
The cached representation is current; the response has no body.
307 Temporary Redirect
Redirects while preserving the method and body.
308 Permanent Redirect
Permanently redirects while preserving the method and body.
400 Bad Request
The request is malformed (bad syntax, invalid framing or headers), so the server will not process it.
401 Unauthorized
Authentication is missing or invalid; WWW-Authenticate is required.
403 Forbidden
The server understood the request but refuses to fulfill it.
404 Not Found
The requested resource is unavailable; it may previously have existed.
405 Method Not Allowed
The method is unsupported for the resource; Allow is required.
409 Conflict
The request conflicts with the resource’s current state.
422 Unprocessable Content
The request is well formed, but its content fails validation (for example a required field is missing or a value is out of range).
429 Too Many Requests
A rate limit was exceeded; Retry-After may specify a delay.
500 Internal Server Error
The server encountered an unexpected condition.
502 Bad Gateway
A gateway or proxy received an invalid upstream response.
503 Service Unavailable
The service is temporarily unavailable.
504 Gateway Timeout
A gateway or proxy timed out waiting for an upstream response.
Example and Real-System Behavior
For a request to /articles/42, possible outcomes include:
200 OK with the article when it exists and access is permitted.
304 Not Modified when the client already has a current cached copy.
401 Unauthorized when valid credentials are required but absent.
403 Forbidden when the user is authenticated but lacks permission.
404 Not Found when no matching resource is available.
A command such as curl -i https://example.com/articles/42 displays the response status and headers for inspection.
In deployed systems, the component producing the response may not be the application. A reverse proxy such as nginx, a CDN, or a load balancer may return 403, 429, 502, 503, or 504 before traffic reaches the origin. Conversely, an origin server or its application code may generate 400, 401, 403, 404, or 409.
Best Practices and Common Pitfalls
Handle the exact code: 200, 201, 202, 204, and 206 have different semantics.
Do not classify every 4xx as a client defect: 429, for example, may require delayed retrying.
Retry carefully: retry temporary failures such as 429, 502, 503, and 504 for idempotent operations using exponential backoff and jitter.
Preserve idempotency: do not blindly repeat a POST after an uncertain network failure.
Use required headers: include WWW-Authenticate with 401 and Allow with 405; add Retry-After when it provides useful retry guidance.
Distinguish authentication from authorization: use 401 for missing or invalid authentication and 403 when the request is understood but access is denied.
Avoid assuming every 5xx is a crash: it can also represent a dependency failure, timeout, overload, or invalid upstream response.
57
How do HTTP/1.1, HTTP/2, and HTTP/3 differ?
KnownRevise
HTTP/1.1, HTTP/2, and HTTP/3 are versions of the Hypertext Transfer Protocol with different transport, framing, multiplexing, and security designs. HTTP/1.1 uses human-readable control lines and headers over TCP, HTTP/2 uses binary framing and multiplexed streams over TCP, while HTTP/3 carries HTTP framing over QUIC, which runs over UDP.
Read full answerHide full answer
Applies toHTTP/1.1 (RFC 9112 for message syntax and framing; RFC 9110 for semantics), HTTP/2 (RFC 9113), HTTP/3 (RFC 9114), and QUIC (RFC 9000/9001)
Core Architecture
Feature
HTTP/1.1
HTTP/2
HTTP/3
Transport
TCP
TCP
QUIC over UDP
Message format
Text-based control lines and headers; body may be binary
Binary frames
Binary frames
Multiplexing
Limited; usually one request at a time per connection
Multiple concurrent streams
Multiple concurrent streams
Header compression
None
HPACK
QPACK
TLS requirement
Commonly used but not required by HTTP itself
Not required by HTTP/2 itself; usually used with TLS
Requires TLS 1.3
Connection migration
Limited
Limited by TCP connection identity
Supported through QUIC connection IDs
Server push
Not defined
Deprecated in current HTTP/2 specification
Not supported
At the OSI layer, all three are application-layer protocols. In the TCP/IP model, HTTP/1.1 and HTTP/2 normally use TCP, whereas HTTP/3 uses QUIC above UDP. QUIC implements reliable delivery, congestion control, flow control, and stream multiplexing itself instead of relying on TCP.
Multiplexing and Head-of-Line Blocking
HTTP/1.1: A persistent TCP connection can carry multiple requests sequentially. Although request pipelining exists, responses must generally arrive in request order, so one slow response can block later responses. Most browsers therefore use several connections instead of aggressive pipelining.
HTTP/2: Multiplexes many requests as independent streams over one TCP connection. This removes the HTTP/1.1 response-ordering problem. However, TCP exposes a single ordered byte stream: if a TCP segment is lost, later data cannot be delivered until the missing segment is retransmitted. That transport-level head-of-line blocking can delay every HTTP/2 stream.
HTTP/3: QUIC maintains independent reliable streams. A lost packet usually affects only the stream that referenced it, allowing other streams to continue. QUIC still performs connection-level congestion control, but it avoids TCP’s cross-stream delivery blockage.
For example, if one HTTP/2 request downloads a large file and another retrieves a small API response, loss of a TCP segment may delay both requests. With HTTP/3, the small response can usually proceed independently.
Framing, Compression, and Encryption
HTTP/1.1 control lines and headers are human-readable, which simplifies inspection but creates repeated overhead. The message body is not necessarily text and may be binary; its framing is determined by mechanisms such as Content-Length, chunked transfer coding, or connection closure, depending on the message.
HTTP/2 replaces textual messages with binary frames. It uses HPACK to compress repeated headers through a static table, a dynamic table, and indexed representations. Frame types include HEADERS, DATA, RST_STREAM, SETTINGS, and WINDOW_UPDATE.
HTTP/3 also uses binary frames but separates HTTP semantics from QUIC’s transport behavior. QPACK has a larger static table than HPACK and maintains separate dynamic-table contexts for request and response header fields. These features can improve compression, but additional field-section references and metadata add complexity. HTTP/3 requires TLS 1.3, and QUIC integrates the TLS handshake with connection establishment rather than running TLS as a separate layer over TCP.
Connection Setup and Practical Behavior
HTTP/1.1 over TLS 1.3: Usually requires one TCP round trip followed by one TLS round trip for a new connection, though session resumption can reduce later costs.
HTTP/2 over TLS 1.3: Has the same basic TCP and TLS establishment costs as HTTP/1.1, but reuses one connection for many streams.
HTTP/3: QUIC combines transport and TLS processing, typically allowing useful requests after one network round trip.
Real-world clients and servers, including browsers, CDNs, reverse proxies, and tools such as curl, commonly support more than one version. They negotiate the protocol with TLS Application-Layer Protocol Negotiation (ALPN). HTTP/3 also depends on UDP being available; networks that block or throttle UDP may cause fallback to HTTP/2 or HTTP/1.1.
Trade-offs and Selection
Consideration
HTTP/1.1
HTTP/2
HTTP/3
Simplicity and broad compatibility
Best
Very good
Good and improving
Concurrent requests
Weak
Strong
Strong
Loss isolation
Limited
Limited by TCP
Better through QUIC
Middlebox compatibility
Highest
Generally high
Lower than TCP-based HTTP
Connection migration
Weak
Weak
Strong
Typical deployment
Legacy fallback
Widely deployed
Increasingly common
HTTP/3 generally offers better behavior on lossy or high-latency mobile networks, but its UDP dependency and more complex implementation can limit deployment. HTTP/2 remains a practical default for TCP-only environments, while HTTP/1.1 remains necessary as a compatibility fallback. Protocol choice should therefore be considered alongside network conditions, intermediaries, observability tooling, and the complete browser or client–server support matrix.
58
How does HTTPS differ from HTTP in computer networks?
KnownRevise
HTTPS is HTTP transmitted over TLS, adding encryption, message integrity, and server authentication to the application-layer HTTP protocol. HTTP sends data in clear text, while HTTPS protects requests and responses between the client and server.
Read full answerHide full answer
Applies tocomputer networks (HTTP/1.1, HTTP/2, HTTP/3, and TLS 1.3)
Core Differences
Property
HTTP
HTTPS
Transport security
None
TLS encryption and integrity protection
Server identity
Not verified cryptographically
Verified through a certificate and trusted CA
Default port
80
443
URL scheme
http://
https://
Data exposure
Readable on the network path
Encrypted on the network path
Common modern versions
HTTP/1.1, HTTP/2 in cleartext
HTTP/1.1 or HTTP/2 over TLS; HTTP/3 over QUIC with TLS 1.3
HTTP itself remains a stateless request-response application protocol: a client sends a request such as GET /products, and the server returns a response containing a status code, headers, and an optional body. HTTP may use cookies, sessions, or tokens to maintain application state, but those mechanisms are separate from the core protocol.
HTTPS places this exchange inside a TLS-protected channel. In a typical TLS 1.3 handshake:
The server presents a certificate containing its identity and public key.
The client validates the certificate against a trusted certificate authority.
Client and server establish shared cryptographic keys.
Subsequent HTTP messages are encrypted and protected against modification.
How It Works in Practice
When a browser visits https://example.com/api, it opens the appropriate protected connection, negotiates the protocol version, and sends an HTTP request. The response might contain JSON, HTML, images, or other media.
In a textbook TCP/IP model, HTTP commonly uses TCP. Real systems use several arrangements:
HTTP/1.1: Uses one request stream over TCP; browsers may open several TCP connections for parallel requests.
HTTP/2: Uses one TCP connection with multiplexed streams, binary framing, and header compression. Modern browsers and servers usually negotiate HTTP/2 through TLS ALPN.
HTTP/3: Uses QUIC over UDP. QUIC provides its own reliable transport and congestion control, while TLS 1.3 is integrated into the QUIC handshake.
Therefore, “HTTPS” does not uniquely mean HTTP/1.1 over TLS. It can securely carry HTTP/1.1, HTTP/2, or HTTP/3.
Security Properties
HTTPS provides three main guarantees:
Confidentiality: Network observers cannot directly read request or response contents.
Integrity: TLS detects modification of protected messages.
Server authentication: A valid certificate verifies that the client connected to the claimed domain, subject to CA trust and correct hostname validation.
TLS 1.3 also provides forward secrecy: compromising the server’s long-term private key does not allow an attacker to decrypt previously recorded sessions.
HTTPS does not guarantee that the server’s application is secure, that its content is truthful, or that the destination IP address remains hidden. DNS lookups and the server’s IP address may still be visible, and vulnerabilities can exist inside the web application.
Trade-offs and Common Pitfalls
CPU and latency cost: TLS requires cryptographic handshakes and encryption. TLS 1.3 and connection resumption reduce repeated handshake cost.
Certificate management: Expired, mismatched, or untrusted certificates cause browser warnings.
Mixed content: An HTTPS page loading insecure HTTP resources may be blocked or weakened by browser security rules.
Not all traffic is protected: APIs, databases, and services outside the browser require their own TLS configuration.
Encryption is only one control: HTTPS does not replace authentication, authorization, input validation, patching, or monitoring.
In Linux systems, administrators commonly inspect HTTPS behavior with curl, openssl s_client, and tcpdump. However, captured HTTP/1.1 or HTTP/2 payloads should appear encrypted at the application layer, while TLS metadata remains visible.
59
What happens during a TLS handshake?
KnownRevise
The TLS handshake is the cryptographic negotiation through which a client and server establish traffic-protection keys and authenticate the server. It normally occurs before an application protocol such as HTTP exchanges data.
TCP connection: The client establishes a TCP connection, and TLS runs as a protocol above it.
ClientHello: The client offers supported TLS versions, AEAD cipher suites, key-exchange groups, and usually one or more key_share entries. It may also offer a PSK for session resumption; a PSK-only offer (psk_ke mode) can omit key shares entirely.
ServerHello or retry: The server selects the TLS version, cipher suite, and group and returns its key share in ServerHello. If the client supplied no share for the selected group, the server sends a HelloRetryRequest; the client then sends a second ClientHello containing the requested share.
Encrypted server flight: The server sends encrypted EncryptedExtensions and, for certificate-based authentication, its Certificate, CertificateVerify, and Finished messages. A PSK-based resumption can omit the certificate.
Client validation and response: The client validates the server’s certificate and its signature over the handshake transcript, then sends its encrypted Finished message.
Application data: Both sides derive application traffic keys and begin exchanging encrypted records.
With (EC)DHE, the ephemeral shared secret enters the TLS 1.3 HKDF-based key schedule. It produces separate handshake and application traffic secrets for each direction; each AEAD cipher suite derives a traffic key from the relevant secret. Unlike TLS 1.2, TLS 1.3 does not use separate MAC keys.
What the Handshake Authenticates
With certificate-based authentication, the server proves its identity using an X.509 certificate containing its public key and a certificate chain leading to an anchor trusted by the client.
Certificate chain: Issuer signatures, validity constraints, and the path to a trusted anchor must validate.
Hostname: The certificate’s SAN DNS identifier must match the requested hostname. Common Name fallback is legacy and implementation-dependent.
Validity period: The certificate must be currently valid.
Proof of possession: CertificateVerify contains a signature made with the corresponding private key over the handshake transcript.
Key constraints: The certificate’s public-key algorithm, signature algorithm, and key usage must be acceptable.
The server can also request a client certificate for mutual TLS, which is commonly used for service-to-service authentication.
TLS 1.3 Versus TLS 1.2
Property
TLS 1.3
TLS 1.2
Encrypted handshake
Handshake messages after ServerHello are encrypted
Many handshake messages are sent in plaintext
Key exchange
Ephemeral (EC)DHE or PSK modes
RSA key transport or ephemeral ECDHE/DHE
Cipher suites
Restricted to AEAD suites
Broader; some legacy constructions are now disabled
Forward secrecy
Provided by (EC)DHE; PSK-only psk_ke is an exception
Depends on the negotiated key exchange; static RSA lacks it
Renegotiation
Not supported
Supported through the secure-renegotiation extension, but often disabled by policy
Early data
Supports 0-RTT data with replay limitations
Does not define TLS 1.3-style 0-RTT data
TLS 1.3 is preferable when both endpoints support it. TLS 1.2 remains useful for legacy compatibility, but it should use ECDHE with strong AEAD cipher suites rather than static RSA key transport.
Concrete HTTPS Example
For https://example.com, the browser resolves the hostname with DNS, opens a TCP connection, performs the TLS handshake, validates the server certificate, and then sends an encrypted HTTP request. The server replies with encrypted HTTP headers and content.
curl -v https://example.com can display the negotiated TLS parameters, certificate details, and HTTP response. A more focused inspection can be performed with openssl s_client -connect example.com:443 -servername example.com.
Security Properties and Common Pitfalls
Confidentiality and integrity: AEAD protects application records from disclosure and undetected modification.
Server authentication: Certificate validation prevents an attacker from silently impersonating the server.
Forward secrecy: With (EC)DHE, later compromise of the server’s long-term authentication key does not reveal previous traffic keys.
Certificate validation must remain enabled: Trusting arbitrary certificates defeats server authentication and enables man-in-the-middle attacks.
0-RTT has replay risk: Early data must not perform non-idempotent operations such as payments without separate replay protection.
TLS is not application authorization: It does not determine whether a user may perform an operation.
Metadata remains visible: IP addresses, ports, traffic volume, and some protocol metadata can still be observed.
60
How do HTTP cookies and sessions differ?
KnownRevise
Cookies are small pieces of data stored by the client and sent automatically with matching HTTP requests. Sessions maintain server-side state across multiple requests, usually by storing a session identifier in a cookie.
Read full answerHide full answer
Applies toHTTP/1.1, HTTP/2, and HTTP/3
Core Concepts
HTTP is stateless: each request is processed independently unless the application explicitly preserves state.
Cookie: A browser-managed key-value value, optionally containing attributes such as Domain, Path, Expires, Max-Age, Secure, HttpOnly, and SameSite.
Session: Server-side application state associated with a unique session identifier, often called a session ID.
How They Work
A server creates a cookie by sending a Set-Cookie response header:
The browser stores the cookie.
On later requests to a matching domain and path, the browser sends it in the Cookie request header.
The server reads the value and uses it to identify the user or retrieve application state.
A typical server-side session flow is:
The client logs in.
The server creates a session and generates a random session ID.
The server stores data such as userId, role, and login time under that ID.
The server sends the session ID to the client in a cookie.
The browser returns the session ID on subsequent requests.
The server looks up the session and authorizes the operation.
For example, after login, the server might create a session containing userId: 42. It sends only an opaque identifier such as abc123 to the browser; the user’s identity and permissions remain on the server.
Cookies vs. Sessions
Aspect
Cookie
Session
Storage location
Primarily in the browser
Primarily on the server
Data visible to the client
Yes
Only the session identifier is normally exposed
Data size
Small; browsers commonly impose a per-domain limit
Larger, limited mainly by server capacity
Revocation
Difficult if the client copies the value; can be replaced or expired
Usually immediate by deleting or invalidating server state
Trust model
The client controls the stored value and can modify it
The server controls session data
Common purpose
Preferences, tokens, identifiers
Authentication and request-to-request state
Performance
Often requires no server lookup
May require a database or cache lookup
A cookie is therefore not necessarily a session. Applications also use cookies for non-sensitive preferences such as language, theme, or recently viewed items.
Session Types and Expiry
Session cookie: Usually has no Expires or Max-Age attribute and is removed when the browser session ends. Exact browser behavior can vary, especially when a browser restores previous sessions.
Persistent cookie: Includes Expires or Max-Age, allowing it to remain until the specified time.
Server-side session: The server stores state in memory, Redis, a database, or another store.
Distributed session: In a scaled application, session data is shared across servers through Redis or a database so any node can handle the request.
Stateless session or token: A signed or encrypted token contains the required claims, so the server need not store session data. This is not a traditional server-side session, although it serves a similar purpose.
Security Practices
Use Secure so cookies are transmitted only over HTTPS.
Use HttpOnly to reduce exposure to JavaScript and XSS-based cookie theft.
Use an appropriate SameSite policy to reduce cross-site request risks. Lax and Strict provide different usability and security trade-offs.
Bind session identifiers to the actual authenticated session and regenerate the identifier after login to prevent session fixation.
Store only an opaque, unpredictable session ID in the cookie; do not store passwords or unnecessary personal data in it.
Validate all session data server-side. Never trust roles, prices, or permissions supplied directly by the client.
Invalidate the server-side session on logout. Deleting the browser cookie alone does not necessarily invalidate a copied token.
Protect state-changing endpoints with CSRF defenses when cookies are used for authentication; SameSite helps but does not replace all CSRF protections.
In real systems such as Linux web servers, Node.js, Java/Spring, and ASP.NET, cookies are managed by the browser and communicated through HTTP, while session storage is implemented by the application framework or an external service such as Redis. TLS protects the cookie in transit, but it does not make an insecurely designed cookie or application session trustworthy.
61
How do SMTP, POP3, and IMAP collaborate for email?
KnownRevise
SMTP is the protocol used for sending email from a client to a server and between servers, while POP3 and IMAP are protocols for retrieving email from a server to a client.
Email delivery involves a chain of agents: the Mail User Agent (MUA) on the client, the Mail Submission Agent (MSA), the Mail Transfer Agent (MTA) on each server, and the Mail Delivery Agent (MDA) that places mail in the recipient’s mailbox. SMTP is used for the submission (client to MSA) and transfer (MTA to MTA) phases. The MSA typically listens on port 587, while relay servers use port 25. After the message is accepted, the MTA routes it to the next hop or the final MDA, where it is stored. The recipient then uses POP3 or IMAP to access the stored messages.
SMTP is a text-based protocol. A typical session begins with EHLO, followed by MAIL FROM, RCPT TO, and DATA. Modern servers require authentication and TLS. The EHLO response lists supported extensions such as STARTTLS, AUTH, and 8BITMIME. Without encryption, credentials and message content are transmitted in cleartext.
POP3 and IMAP: Retrieving Email
Both POP3 and IMAP are client-server protocols for fetching email, but they differ significantly in design.
POP3 (Post Office Protocol 3) downloads messages from the server to the client and, by default, deletes them from the server. This makes it suitable for offline reading on a single device. It uses TCP port 110 (or 995 for implicit TLS). POP3 has no concept of folders; all messages are downloaded into the client’s inbox. Because it removes messages, it does not synchronize across multiple devices.
IMAP (Internet Message Access Protocol) allows clients to view and manage email stored on the server. It supports multiple folders, message flags (seen, answered, flagged), and search. IMAP keeps messages on the server, enabling synchronization across devices. Default port is 143 (or 993 for IMAPS). Clients can selectively fetch message headers or parts of the body to save bandwidth.
Feature
POP3
IMAP
Server storage
Downloads and usually deletes
Keeps messages on server
Folders
No folder support
Multiple folders
Multiple devices
Not synchronized
Synchronized
Offline access
Yes, after download
Possible with cached copy
Default port
110
143
Complexity
Simple
More complex
Security and Best Practices
Always use TLS (STARTTLS or implicit TLS) to protect credentials and email content.
Prefer IMAP over POP3 for multi-device access.
Use strong authentication; OAuth 2.0 is increasingly supported.
Configure firewalls to block unnecessary ports; port 25 is often blocked for residential users—use 587 for submission.
Avoid sending sensitive data over email without additional encryption (e.g., PGP).
62
How does FTP differ between active and passive modes?
KnownRevise
FTP (File Transfer Protocol) is an application-layer protocol for transferring files between a client and a server over TCP. It uses two separate channels: a control channel for commands and responses and a data channel for file contents or directory listings. The main difference between active and passive modes is which side initiates the data connection.
Read full answerHide full answer
Applies toFTP (RFC 959, with RFC 2428 extensions for EPRT and EPSV)
How FTP Works
FTP follows a client-server model and operates at the application layer of the TCP/IP model, corresponding roughly to the application, presentation, and session layers of the OSI model.
The client first opens a TCP control connection to the server, normally using server port 21. It then authenticates with commands such as USER and PASS, while the server returns responses on the same connection.
A separate data connection is opened for each transfer command, such as:
RETR: download a file
STOR: upload a file
LIST: list a directory
Who opens it depends on the mode, as described below. Commands such as DELE (delete a file) or CWD run entirely on the control connection.
FTP is not inherently secure. Usernames, passwords, commands, and transferred data are normally sent in plaintext. FTPS adds TLS protection, while SFTP is a different protocol carried over SSH.
Active Mode
In active mode, the client tells the server which IP address and port to use for the data connection. The server then opens the data connection from its own server-side data port, traditionally TCP port 20, to the client.
For example, the control connection is client -> server:21, while the data connection is server:20 -> client:50000.
The client sends a PORT command containing its address and selected port. The server responds with a successful 200 status before opening the data connection.
Active mode can work well when the client is directly reachable and can accept an incoming server connection. However, it commonly fails when:
The client is behind NAT
A firewall blocks incoming connections
The server cannot route to the client’s advertised address
Passive Mode
In passive mode, the server selects a data port, tells the client which address and port to use, and waits. The client then initiates the data connection to that server port.
For example, the control connection is client -> server:21, while the data connection is client:50001 -> server:40000.
The client sends PASV, and the server replies with 227 Entering Passive Mode containing the address and port. Modern clients often send EPSV, the extended passive command, which works with IPv6; the server replies with 229 and a port.
Passive mode is generally more compatible with NAT and firewalls because the client initiates both connections. This is why many current FTP clients use passive mode by default or provide it as the recommended option.
Active vs. Passive Comparison
Aspect
Active mode
Passive mode
Data connection initiator
Server
Client
Typical data path
server:20 -> client:high-port
client:high-port -> server:high-port
Port negotiation
Client sends PORT (or EPRT)
Client sends PASV or EPSV; server replies 227 or 229 with the port
NAT and firewall compatibility
Often problematic
Usually better
Best deployment
Client directly reachable
Typical Internet and NAT environments
Main security concern
Server must reach the client
Client must reach the server
Practical Example
Suppose a user downloads report.pdf:
The client connects to the FTP server on port 21.
It authenticates with USER and PASS.
The client requests the file with RETR report.pdf.
In passive mode, the client opens a separate TCP connection to the server’s advertised data port.
The server sends the file over that data channel.
The control connection remains available for status messages and further commands.
Although the control and data connections are separate TCP connections, they are logically related: commands on the control connection request and control the corresponding data transfers.
Security and Operational Considerations
Plain FTP is unencrypted: use FTPS or SFTP when confidentiality and integrity matter.
SFTP is not FTP: SFTP is an SSH file-transfer protocol and does not use FTP’s PORT/PASV mechanism.
Use explicit FTPS when regulatory or organizational requirements call for TLS-protected file transfer.
Avoid active mode across untrusted networks unless inbound server-to-client traffic is explicitly permitted.
Check server logs and firewall rules when diagnosing transfers, since successful authentication does not guarantee that the data channel works.
Use ftp or curl only in controlled environments for testing plaintext FTP. For example, curl --ftp-pasv ftp://server/file explicitly requests passive behavior.
63
What is SSH and how does it secure remote access?
KnownRevise
SSH (Secure Shell) is a cryptographic network protocol that provides encrypted remote login and file transfer between computers. It authenticates the client and server, protects confidentiality and integrity, and supports secure command execution, file transfer, and port forwarding.
Read full answerHide full answer
Applies toSSH protocol version 2 (RFC 4251–4254 and later SSHv2 extensions) across OpenSSH versions implementing SSHv2
How SSH Works
SSH normally runs over TCP, commonly using port 22. In the TCP/IP model, it is an application-layer protocol; in the OSI model, it provides application-layer services while using the transport layer for reliable delivery.
A typical SSHv2 connection follows these steps:
TCP connection: The client connects to the SSH server, and both sides exchange protocol-version information.
Key exchange: The client and server negotiate cryptographic algorithms and derive shared keying material. The derived secret itself is not transmitted over the network.
Server authentication: The server presents a host key. The client verifies it against its known_hosts data, helping detect server impersonation.
Session-key setup: Both sides derive keys used for encryption and integrity protection.
User authentication: The server verifies the user using a password, public key, keyboard-interactive challenge, or another configured method.
Secure channels: The authenticated session opens channels for a remote shell, command execution, SFTP, or TCP forwarding.
SSHv2 separates the protocol into a transport layer, an authentication layer, and a connection layer. The connection layer multiplexes multiple logical channels over one encrypted TCP connection.
Security Properties
SSH provides several important security guarantees:
Confidentiality: Session traffic is encrypted, so captured packets do not normally reveal passwords, commands, files, or session data.
Integrity: Message authentication codes or authenticated-encryption tags detect modified packets, while packet sequence numbers prevent replay within a connection.
Server authentication: A host key identifies the server. Users must investigate unexpected or changed keys rather than blindly accepting them.
Client authentication: Public-key authentication proves possession of the corresponding private key without transmitting that private key.
Forwarding control: Port and agent forwarding can expose internal services or credentials if configured carelessly.
SSH does not protect against a compromised server, endpoint malware, malicious commands from an authorized user, weak credentials, or an administrator who accepts a malicious host key. It secures the communication channel; it does not make the remote system trustworthy.
Common Uses
Use
Description
Remote shell
Runs an interactive command-line session on a remote host
Remote command
Executes one command and returns its result
File transfer
Uses SFTP; the legacy SCP protocol is obsolete and should not be selected
Port forwarding
Connects local or remote TCP ports through the SSH server
Git and automation
Provides authenticated transport for tools that support SSH URLs
Real deployments include Linux servers, Windows OpenSSH, network appliances, and cloud virtual machines. Administrators commonly combine SSH with firewalls, restricted accounts, sudo, multi-factor authentication, bastion hosts, and centralized audit logs. SSH is also commonly used by Git for repository access and by automation systems for remote administration.
Operational Considerations
Password authentication: Useful for initial setup, but public-key authentication is generally preferable because a stolen server-side password hash can expose accounts to offline guessing.
Multi-factor authentication: SSH does not impose one universal MFA mechanism; deployments can use keyboard-interactive authentication through PAM, FIDO2-backed keys, or organizational access systems.
Host-key management: Use trusted provisioning, configuration management, or carefully verified fingerprints rather than unconditional acceptance of unknown keys.
Key protection: Store private keys securely, use passphrases or hardware-backed agents, and restrict file permissions appropriately.
Least privilege: Run commands with only the privileges they require and review access to privileged accounts.
Best Practices and Trade-offs
Prefer Ed25519 keys; where RSA is required, use an adequate key size and modern RSA/SHA-2 signatures rather than legacy ssh-rsa with SHA-1.
Restrict logins with firewall rules, network segmentation, jump hosts, and AllowUsers or AllowGroups in sshd_config.
Disable root login where organizational policy permits it, and use sudo for controlled privilege elevation.
Disable unnecessary forwarding with directives such as AllowTcpForwarding and AllowAgentForwarding; use agent forwarding sparingly because a compromised remote host may misuse the forwarded agent.
Keep OpenSSH patched and avoid re-enabling obsolete algorithms.
Use SFTP instead of unencrypted FTP for sensitive file transfers.
SSH offers strong protection with relatively low setup cost, but its scope differs from a VPN. A VPN protects broad network traffic between endpoints, whereas SSH protects specific sessions, commands, and forwarded channels over an existing TCP connection.
64
What happens when you enter a URL in a web browser?
KnownRevise
The browser follows a web request lifecycle: it parses the URL, resolves the hostname, establishes or reuses a transport connection, exchanges HTTP messages, and parses and renders the returned content. Caches, service workers, redirects, security policies, and parallel resource loading can alter the exact sequence.
Read full answerHide full answer
Applies toWeb platform request lifecycle using DNS, TCP/IP, TLS 1.3, HTTP/1.1, HTTP/2, and HTTP/3
URL Parsing and Cache Lookup
The browser first parses the URL into components such as scheme, hostname, port, path, query, and fragment. It then determines whether the request can be served locally:
The HTTP cache may already contain a fresh response.
A service worker may intercept the request and return a cached or generated response.
Browser security policies such as HTTPS enforcement and HSTS may require or upgrade the connection.
A previously opened connection may be reused, so DNS resolution and a new transport handshake might not be necessary.
If a network request is required, the browser needs an IP address for the hostname.
DNS and Network Routing
The browser first checks its own DNS cache. If no usable entry exists, it uses the operating system’s resolver or a browser-provided resolver to contact a recursive DNS server, possibly through the host resolver API or encrypted DNS.
If the recursive server has no cached answer, it normally performs iterative lookups:
A root server returns a referral to the appropriate TLD server.
The TLD server returns a referral to the authoritative name server.
The authoritative server returns the requested A or AAAA record and its TTL.
The resulting addresses may be cached according to their TTL. dig can help inspect DNS records and resolution behavior.
The browser passes the destination address to the operating system. The host uses its routing table to select a next hop. IP packets then cross the Internet as link-layer frames over technologies such as Ethernet or Wi-Fi, with each router forwarding traffic toward the destination. Firewalls, NAT, load balancers, and other network equipment may also participate.
Transport Connection and TLS
For HTTP/1.1 and HTTP/2, the browser opens a TCP connection using a three-way handshake:
The client sends SYN.
The server replies with SYN-ACK.
The client responds with ACK.
For HTTPS using HTTP/1.1 or HTTP/2, TLS runs above TCP. In a full TLS 1.3 handshake, the client sends a ClientHello containing a key share and supported parameters. The server responds with ServerHello, followed by encrypted handshake messages including its certificate and Finished. The client validates the certificate chain, hostname, and signatures, and the peers derive session keys. This normally adds one network round trip after TCP setup.
A resumed TLS 1.3 handshake can use a pre-shared key. Zero-round-trip early data may also be permitted, but it can be replayed and therefore requires appropriate application safeguards.
HTTP/3 differs: it uses QUIC over UDP and integrates TLS 1.3 into the QUIC handshake, so it does not use the TCP three-way handshake.
HTTP Exchange
The browser sends an HTTP request containing the method, target, headers, and sometimes a body. For example, an HTTP/1.1 request may include Host, User-Agent, Accept, and Cookie headers. HTTP/2 and HTTP/3 represent equivalent semantic headers using their respective binary framing formats.
The server returns a status, headers, and possibly a body. Responses include successful 2xx results, redirects in the 3xx range, authentication challenges, and errors. The browser follows redirects when permitted and applies caching and cookie policies to the exchange.
Rendering, Subresources, and Performance
The browser incrementally parses HTML into the DOM, constructs the CSSOM, creates a render tree, performs layout, paints, and composites the result. JavaScript can modify the DOM and trigger additional requests. Stylesheets, scripts, images, fonts, and other subresources may require further requests, but the browser can reuse DNS results, HTTP/2 streams, HTTP/3 streams, and existing connections.
DNS and HTTP caching: Reduce repeated lookups and transfers; Cache-Control and ETag are common HTTP caching mechanisms.
Connection reuse: Avoids repeating DNS resolution and transport handshakes.
TLS 1.3: Reduces full-handshake latency to one RTT after transport establishment.
CDNs: Place content closer to users and reduce network latency.
Service workers: Can implement application-controlled caching, offline behavior, and custom request handling; HTTP’s stale-while-revalidate is a separate cache directive.
Browser developer tools provide the most representative view of these stages because real browsers add speculative connections, parallel resolution, request prioritization, privacy controls, and protocol optimizations beyond the textbook sequence.
65
What distinguishes forward proxy servers from reverse proxy servers?
KnownRevise
A proxy server is an intermediary that receives a client request and communicates with the destination server on the client’s behalf. A forward proxy represents outbound clients, while a reverse proxy represents one or more origin servers and is commonly used for load balancing, caching, and TLS termination.
Read full answerHide full answer
Applies tocomputer networks (general TCP/IP and OSI concepts)
How Proxies Work
Proxies may operate at different layers. HTTP proxies are application-layer proxies, while SOCKS proxies can relay application traffic using transport-layer protocols. TCP proxies operate at the transport layer and forward byte streams without interpreting HTTP messages.
A proxy can:
Forward requests to an origin server.
Cache frequently requested resources.
Authenticate users or restrict destinations.
Inspect or modify application-layer data.
Terminate and re-establish TLS connections.
Distribute traffic across multiple backend servers.
Hide the address of one endpoint from the other.
A transparent proxy is installed without requiring client configuration. An explicit proxy requires clients to select the proxy, commonly through browser settings or application configuration.
Forward Proxy Versus Reverse Proxy
Aspect
Forward Proxy
Reverse Proxy
Represents
The client or user group
The origin server or server group
Typical traffic direction
Client to external services
External clients to internal services
Client awareness
Usually knows and configures the proxy
Usually believes the proxy is the actual service
Destination selection
User or proxy policy selects the destination
Proxy selects a configured backend
Address exposure
The origin normally sees the proxy’s source IP; forwarding headers may also expose the client IP
The backend sees the proxy’s source IP; forwarding headers may additionally carry the original client IP
Typical uses
Controlled internet access, content filtering, outbound caching
Load balancing, reverse caching, SSL termination, API gateways
Example
Squid forward proxy
Nginx, HAProxy, or Envoy configured as a reverse proxy
The distinction is based on which side the proxy represents, not merely on where the proxy is physically located.
Concrete Request Flows
For a forward proxy:
A browser requests https://example.com.
The forward proxy accepts the request or creates a CONNECT tunnel.
The proxy connects to example.com.
The response travels through the proxy back to the browser.
This allows an organization to control outbound access and record connection metadata. With CONNECT, the proxy normally forwards encrypted TLS traffic without decrypting it. Inspecting that traffic requires an explicitly authorized TLS-interception design.
For a reverse proxy:
A client sends an HTTPS request to api.example.com.
The reverse proxy terminates the TLS connection.
The proxy selects a healthy backend, such as 10.0.1.20:8080.
The backend returns the response through the proxy.
The reverse proxy returns that response to the client.
Several clients can therefore reach a public endpoint while requests are distributed across multiple private backend instances.
Security and Operational Trade-offs
Forward proxy risk: Clients may attempt to bypass it for disallowed destinations. DNS, routing, firewall, and endpoint policies must be coordinated rather than relying on the proxy alone.
Reverse proxy risk: Misconfigured forwarding headers can let clients spoof source addresses. Strip untrusted incoming forwarding headers and add trusted values only at the edge; backends should trust forwarding headers only from known proxies.
TLS termination: A reverse proxy can simplify certificate management, but traffic between the proxy and backend should use TLS when it leaves a trusted network boundary.
Failure impact: A proxy can become a latency bottleneck or single point of failure. Health checks, redundancy, and capacity planning are important.
Application behavior: Path rewriting, cookies, authentication, WebSockets, and client IP handling may differ from direct-to-backend communication.
Defense in depth: A proxy can provide rate limiting, request-size limits, access logging, and WAF functionality, but it does not replace secure application code.
Choosing the Appropriate Proxy
Use a forward proxy when the main goal is to control or mediate client access to external destinations. Use a reverse proxy when the goal is to expose one reliable service endpoint while operating one or more origin servers.
In real systems, Squid is commonly used as a forward proxy, while Nginx, HAProxy, Envoy, and cloud load balancers commonly perform reverse-proxy duties. Linux also supports transparent forwarding through packet-filtering mechanisms, whereas traditional textbook models usually describe forward and reverse proxies as separate application-level arrangements.
66
How does a CDN improve content delivery performance?
KnownRevise
A content delivery network (CDN) is a distributed system of proxy servers that caches and delivers content from locations closer to users. It improves performance by reducing network distance, offloading traffic from the origin server, and often terminating TLS connections at the edge.
Read full answerHide full answer
Applies tocomputer networks (HTTP content delivery and DNS-based routing)
How It Works
A CDN is primarily an application-layer reverse proxy supported by DNS and the Internet routing system.
A client requests content such as https://example.com/image.jpg.
DNS returns an address associated with a nearby CDN edge location. Many CDNs use Anycast, allowing multiple locations to advertise the same IP address while the network directs traffic to a suitable location.
The edge server checks its cache.
On a cache hit, the edge server immediately returns the cached object without contacting the origin.
On a cache miss, it retrieves the object from the origin, caches it according to the caching policy, and forwards it to the client.
CDNs commonly cache static resources such as images, videos, JavaScript, CSS, fonts, and downloadable files. They can also cache or dynamically route API responses.
Performance Improvements
Improvement
How the CDN helps
Lower latency
Content is served from an edge location closer to the user, reducing the round-trip time for the client.
Higher origin capacity
Repeated requests are served from the cache, reducing traffic and computation on origin servers.
Greater throughput
Edge locations distribute bandwidth demands across many servers and networks.
Better scalability
The origin can handle sudden traffic increases without serving every request directly.
Improved availability
Redundant edge locations can continue serving cached content if an origin is overloaded or temporarily unavailable.
Connection optimization
Edge servers can maintain efficient backend connections and often reuse connections between clients and the CDN.
The largest improvement usually occurs for cacheable content with a high cache-hit ratio. For uncached or unique content, the client still communicates with the origin, so the benefit may be limited.
Concrete Example
Suppose the origin is in another country and a user downloads a 10 MB video file:
Without a CDN: Most video bytes may cross a long-distance path between the origin and the user. The origin also handles the full transfer.
With a CDN: The first request may retrieve the video from the origin. Later requests are served from a nearby edge location, reducing transfer latency and origin bandwidth consumption.
Cacheability is commonly controlled with HTTP response headers such as Cache-Control, Expires, and ETag. A Content-Location header is also used in some CDN and caching configurations.
Trade-offs and Limitations
Cache invalidation: Content may remain cached longer than intended unless expiration and purge mechanisms are configured correctly.
Stale content: Long cache lifetimes improve performance but make updates slower to reach users.
Operational complexity: DNS routing, cache keys, purging, origin shielding, and failover require careful configuration.
Cost: Providers charge for traffic, requests, storage, or premium features. Multi-CDN routing adds further complexity.
Privacy considerations: CDNs can observe client metadata, but their data-processing practices differ among providers.
Security trade-offs: A CDN can absorb volumetric attacks, but a poorly configured origin may still be exposed or bypassed.
A CDN does not eliminate the Internet’s propagation delay, and it cannot accelerate every resource equally. Dynamic HTML, personalized responses, and frequently changing APIs often have lower cache-hit ratios.
Best Practices
Use versioned asset URLs or fingerprints for frequently updated files, such as app.4a7c2.js.
Set Cache-Control according to how quickly each content type changes.
Keep Set-Cookie responses out of shared caches unless the CDN explicitly supports the required cookie-based cache key.
Use a purge or cache-invalidation mechanism for urgent updates.
Protect the origin so clients cannot bypass the CDN when direct origin access is not intended.
Load-test dynamic routes separately from cacheable content to avoid overestimating CDN benefits.
67
What are layer 4 and layer 7 load balancing in load balancers?
KnownRevise
A load balancer distributes client traffic across multiple servers or service instances so they can share workloads, remain available, and scale horizontally. The main distinction is the OSI layer understood by the balancer: layer 4 operates at the transport layer, while layer 7 operates at the application layer.
Read full answerHide full answer
Applies toall versions of OSI and TCP/IP computer-networking concepts
Core Functions
A load balancer usually provides:
Traffic distribution: Selects a backend using algorithms such as round-robin, weighted round-robin, least-connections, or hashing.
Health checks: Periodically verifies that backends are reachable and removes unhealthy ones from the pool.
Virtual endpoint: Presents one IP address or DNS name to clients while traffic is forwarded to several real servers.
Connection management: Maintains backend connections and manages client connection limits.
Security functions: May provide TLS termination, rate limiting, access control, and protection against some attacks.
A load balancer can operate as a reverse proxy, accepting client connections on its public address and opening corresponding connections to selected backends.
Layer 4 Versus Layer 7
Aspect
Layer 4 load balancing
Layer 7 load balancing
OSI layer
Transport layer
Application layer
Common protocols
TCP and UDP
HTTP, HTTPS, gRPC, and other understood application protocols
Selection information
Client IP, port, protocol, and connection or flow tuple
HTTP method, path, host, headers, cookies, and sometimes body or metadata
Granularity
Usually one backend decision per TCP connection or UDP flow
One backend decision per HTTP request
TLS handling
Usually passes TLS traffic through unchanged
Can terminate TLS and inspect HTTP, or re-encrypt traffic to backends
Performance
Lower processing and latency overhead
Higher CPU and memory requirements
Protocol support
Works with arbitrary TCP/UDP services
Requires support for the specific application protocol
Typical use cases
Database connections, TCP services, game servers, generic port forwarding
Web applications, APIs, microservices, and content-based routing
Both approaches can perform health checking and distribute traffic among healthy backends. Their fundamental difference is how much of each request they can understand.
How Layer 4 Balancing Works
A layer 4 balancer examines transport-layer information such as source and destination IP addresses, ports, and protocol. It then forwards the connection or flow to a backend.
Two common implementations are:
NAT-style forwarding: The balancer rewrites network addresses and ports while forwarding the original payload.
TCP proxying: The balancer accepts the client’s TCP connection and creates a separate TCP connection to the selected backend.
A TCP connection is assigned to one backend for its lifetime. Later requests on that connection normally reach the same backend, but different connections can be distributed independently. This is why layer 4 balancing cannot normally select a backend according to an HTTP URL.
How Layer 7 Balancing Works
A layer 7 balancer understands an application protocol. For HTTP, it can inspect fields such as:
Host
Request path, such as /api/orders
HTTP method, such as GET or POST
Cookies
Authorization headers
Content type
This enables routing rules. For example, /api traffic can go to API servers while /images goes to a CDN or storage-backed service.
For HTTPS, a layer 7 balancer that terminates TLS must possess the server certificate and its corresponding private key. It can then decrypt the connection, inspect the HTTP request, choose a backend, and usually establish a new TLS connection to that backend. A layer 4 balancer normally forwards encrypted TLS bytes without understanding the HTTP request inside them.
Concrete Example
Suppose two API servers, 10.0.0.10 and 10.0.0.11, sit behind the public address 192.0.2.10.
With layer 4 balancing, each incoming TCP connection is forwarded to one server based on a balancing algorithm. All requests carried over an established connection reach that same server, regardless of their URL.
With layer 7 balancing, requests to /checkout could go to 10.0.0.10, while requests to /catalog go to 10.0.0.11. Each request is routed independently, allowing better service specialization and rollout control.
Real systems such as HAProxy, Nginx, Envoy, and cloud load-balancing services implement these models. Some products expose both layer 4 and layer 7 balancing modes. In a chained architecture, a layer 4 frontend can forward traffic to a layer 7 proxy, which then performs HTTP-aware routing.
Trade-offs and Best Practices
Choose layer 4 when low overhead, broad protocol compatibility, or transparent TCP/UDP forwarding matters more than request-level routing.
Choose layer 7 when routing must depend on URL, headers, cookies, HTTP methods, or other application metadata.
Use health checks: A backend should receive traffic only when it is ready, not merely when its process is running.
Account for persistent state: Layer 7 request-level routing may send consecutive requests to different backends, so shared databases, caches, or session storage may be necessary.
Handle TLS deliberately: Decide whether TLS termination occurs at the load balancer, passes through unchanged, or is re-encrypted to backends.
Avoid naive IP hashing: It can create uneven distributions when clients share NAT gateways or when a small number of clients generate most traffic.
68
What are the main types of computer firewalls?
KnownRevise
A firewall is a security control that permits or blocks network traffic according to defined rules, protecting networks and hosts from unauthorized access. Firewalls may operate at different OSI layers, from filtering IP packets to inspecting application-layer content.
Read full answerHide full answer
Applies tocomputer networks (general concepts)
How Firewalls Work
A firewall processes traffic using rules that specify permitted or denied communication. Depending on its type, it may examine:
Source and destination IP addresses, protocols, and ports
TCP flags, connection state, and session metadata
Application data such as HTTP requests or DNS queries
User, process, device, or application identity
A typical processing sequence is:
A packet reaches the firewall.
The firewall identifies the traffic and its relevant fields.
It matches those fields against configured rules.
It allows, rejects, or drops the packet.
It may record the decision in a log.
“Reject” normally sends an error response, while “drop” silently discards the packet. Dropping can slow port scanning but does not by itself hide the firewall.
For example, after a client opens a TCP connection to a server, a stateful firewall can accept the server’s return traffic without a broad inbound rule for that service.
Types by Inspection Method
Firewall type
How it decides
Primary role
Typical limitation
Packet-filtering firewall
Examines packet headers independently
Basic access and service restrictions
Limited connection context
Stateful inspection firewall
Tracks connections and permits related response traffic
Prevents unauthorized sessions and rejects some out-of-state or spoofed traffic
Additional memory and processing
Application-level firewall or proxy
Terminates and inspects application protocols
Protocol-specific request filtering
Must correctly support each protocol
Next-generation firewall
Combines stateful inspection, application awareness, identity, and threat controls
Layered network and application policy enforcement
Greater cost and configuration complexity
Packet-filtering firewall: A packet filter is essentially an access-control list evaluated against source address, destination address, protocol, and port. Classical packet filters are stateless, so each packet is considered separately. They are fast but lack connection context and may mishandle return traffic for allowed outbound connections.
Stateful inspection firewall: A stateful firewall tracks active connection tuples and, where applicable, TCP sequence information. It can accept return traffic because it belongs to a known connection rather than because of a broad independently permissive rule.
Application-level firewall or proxy: An application proxy is an intermediary: it receives a request, may inspect or filter it, forwards it, and returns the response. A web proxy can restrict HTTP methods, URLs, content types, and request rates; an SMTP gateway can scan messages. Proxies can provide strong protocol-specific control, but only for protocols they correctly support.
Next-generation firewall: An NGFW is a vendor product category, not a single protocol mechanism. It typically combines stateful inspection, application identification, intrusion prevention, URL and malware filtering, identity awareness, and logging. Vendor labels differ, so products with the same name may provide different capabilities.
Types by Deployment Location
Deployment type
Scope
Common examples
Network firewall
Protects a network boundary or segment
Data-center appliance, branch firewall
Host firewall
Protects one computer
ufw, firewalld, nftables, Windows Defender Firewall
Personal firewall
Protects an individual user’s computer
Often implemented as a host firewall on a laptop
Cloud firewall
Protects cloud resources and workloads
Cloud security groups and cloud firewall services
These deployment categories overlap with inspection methods. For example, a cloud firewall can be stateful, application-aware, and provided as an NGFW service.
Firewall Versus Related Security Controls
NAT: Translates address or port information; it is not inherently a security control, although restrictive NAT behavior can reduce exposure.
Router ACL: Usually filters packets at interfaces or forwarding points and performs a function similar to a stateless packet filter.
WAF: Focuses specifically on HTTP and HTTPS application attacks rather than general network traffic.
VPN: Encrypts traffic between endpoints. Tunneling itself does not filter traffic, although VPN access policies may restrict which users and connections are permitted.
IDS/IPS: An IDS detects suspicious traffic, while an IPS can inspect inline traffic and block it.
Real-System Considerations and Best Practices
Default-deny: Permit required traffic explicitly instead of allowing broad address or port ranges.
Place controls deliberately: Use host firewalls in addition to perimeter firewalls because a perimeter firewall cannot protect traffic that bypasses it.
Minimize exposure: Permit only necessary ports and management interfaces; administration should use a dedicated path such as a VPN.
Do not rely on obscurity: Security through obscure port numbers is not a substitute for authentication or access control.
Log useful events: Record matches, drops, source identity, interface, and timestamps, while protecting logs from unauthorized modification.
Combine controls: Firewalls should operate with patching, endpoint protection, segmentation, secure configuration, and monitoring.
In Linux, nftables is the preferred modern packet-filtering framework and supports connection tracking; iptables remains widely deployed. Commercial NGFWs add higher-level application, identity, and threat-processing features that a basic Linux packet filter does not provide.
69
How does a VPN protect traffic sent across a network?
KnownRevise
A VPN (Virtual Private Network) creates a logical private connection over a public or shared network. It uses tunneling to carry the original traffic and usually applies encryption and integrity protection, preventing intermediaries from reading or modifying the protected packets.
Authentication: The client and VPN gateway verify their identities using credentials, certificates, cryptographic keys, or a combination of these.
Security negotiation: They agree on encryption, integrity, authentication, and key-exchange mechanisms.
Tunnel establishment: The VPN creates a secure channel between the endpoints.
Encapsulation: The original IP packet is placed inside another packet and sent across the public network.
Verification and decapsulation: The receiving gateway checks the packet’s integrity, decrypts it, removes the outer header, and forwards the original packet.
For example, when an employee connects from home to a corporate network, their laptop sends traffic to the company’s VPN gateway. The gateway validates the session and decrypts the encapsulated packets before forwarding them to internal servers. The Internet may observe connection metadata, but it generally cannot read the VPN-protected payload.
VPN Types
Type
Description
Typical use
Remote-access VPN
Connects an individual device to a private network
Employees accessing internal systems
Site-to-site VPN
Connects two networks through a VPN gateway
Linking branch offices to headquarters
Host-to-host VPN
Protects communication between individual hosts
Server-to-server communication
Overlay VPN
Provides logical connectivity without requiring physical point-to-point links
Cloud networks and virtual infrastructure
A remote-access VPN may use a full tunnel, where all traffic goes through the VPN, or a split tunnel, where only selected traffic uses it.
Common VPN Protocols
Protocol
Important behavior
IPsec
Network-layer security suite providing encryption and integrity; key management commonly uses IKE
OpenVPN
Uses TLS-based cryptography and can operate over UDP or TCP
WireGuard
Modern, lightweight VPN protocol using modern cryptographic primitives
L2TP/IPsec
L2TP provides tunneling, while IPsec supplies encryption and integrity
SSH tunneling
Encrypts traffic through an SSH connection; useful for administrative access but not always treated as a full VPN
L2TP by itself does not encrypt traffic. IPsec is commonly paired with it to provide that protection.
Relationship to the Network Models
In the OSI model, IPsec operates near the network layer, protecting IP traffic. OpenVPN and SSH tunnels operate above the normal IP forwarding path using encrypted transport or application-layer protocols.
VPNs are not a separate physical layer. Instead, they extend the usable network interface: applications send ordinary traffic to a virtual adapter, and the VPN software encapsulates that traffic before sending it through the ordinary Internet-facing interface.
Security Benefits and Limitations
Confidentiality: Encryption prevents network observers from reading packet contents.
Integrity: Authentication mechanisms detect altered or forged packets.
Authentication: Strong VPN deployments can verify both the gateway and the connecting user.
Private addressing: The remote network can use address ranges that are not routed on the public Internet.
Endpoint security: A VPN does not remove malware or protect a device that is already compromised.
Traffic visibility: A VPN provider may still observe connection metadata, and DNS can leak outside the tunnel if it is not configured correctly.
Performance: Encryption, tunneling, and routing add processing overhead and may reduce throughput or increase latency.
Access control: The VPN gateway must still enforce authorization, firewalls, and least-privilege policies.
Practical Considerations
In production, prefer modern authenticated protocols and strong key-management practices. Use full tunneling when all traffic must follow the corporate policy; use split tunneling for performance-sensitive environments, but ensure DNS and sensitive traffic are included. On Linux, administrators can inspect the tunnel with commands such as ip addr, ip route, and ss, while tcpdump can help verify that expected traffic is encrypted on the public interface.
A VPN protects traffic between VPN endpoints; it does not guarantee anonymity, replace HTTPS, or make an untrusted endpoint safe.
70
What are common network attacks in computer networks?
KnownRevise
Common network attacks target confidentiality, integrity, or availability by exploiting protocols, endpoints, or user trust. Major examples include DDoS, man-in-the-middle, ARP spoofing, DNS manipulation, session hijacking, and credential theft; effective defense combines protocol security, traffic filtering, authentication, monitoring, and infrastructure-level protections.
Read full answerHide full answer
Applies tocomputer networks and general TCP/IP security concepts
Common Attack Types
Attack
Primary target
Typical mechanism
DDoS
Availability
Many distributed hosts overwhelm a service or network
Man-in-the-middle (MITM)
Confidentiality and integrity
The attacker secretly relays or modifies communication
ARP spoofing
Local-network integrity
Forged ARP responses redirect traffic through the attacker
DNS poisoning or spoofing
Name resolution
False DNS responses direct users to malicious addresses
Session hijacking
Session confidentiality
A stolen session token or cookie impersonates an authenticated user
Credential theft
User accounts
Passwords, tokens, or MFA codes are captured through phishing or malware
Eavesdropping
Confidentiality
Traffic is observed, commonly on unsecured or improperly configured networks
Protocol exploitation
Hosts and services
Vulnerabilities or malformed messages exploit an implementation
How Major Attacks Work
DDoS
A distributed denial-of-service attack coordinates many compromised devices, called bots, against one target. Common forms include:
Volumetric attacks: Large amounts of UDP, GRE, or other traffic consume bandwidth.
Protocol attacks: Malformed or excessive TCP packets exhaust connection state, such as a TCP SYN flood.
Application-layer attacks: HTTP requests appear legitimate but consume expensive application resources, such as repeatedly invoking an expensive API.
DDoS differs from a single-source DoS attack because mitigation must occur across the target’s network, internet service provider, CDN, or cloud edge. Firewalls alone are often insufficient when the incoming traffic is enormous or distributed across many source networks.
Man-in-the-middle
In a MITM attack, the attacker positions itself between two communicating parties. The attack may be:
Passive: The attacker copies traffic, especially if it is unencrypted.
Active: The attacker modifies messages or injects forged responses.
For example, a user connects to what appears to be a banking website. If certificate validation is absent or incorrectly implemented, the attacker can proxy the connection, observe credentials, and alter responses. HTTPS with correct certificate validation prevents most ordinary MITM interception; HTTP, weak TLS configurations, compromised endpoints, malicious proxies, and compromised trust anchors remain risky.
ARP spoofing
ARP spoofing, also called ARP poisoning, exploits the Address Resolution Protocol used by IPv4 hosts on a local network. An attacker sends forged ARP messages to associate the router’s IP address with the attacker’s MAC address. Other hosts then send frames for the router to the attacker, allowing it to intercept and potentially modify traffic.
ARP spoofing normally affects the same broadcast domain rather than the routed Internet. IPv6 does not use ARP; it uses Neighbor Discovery, which has related but distinct spoofing risks.
Defenses and Detection
Attack
Important defenses
DDoS
Upstream rate limiting, CDN or Anycast distribution, autoscaling, WAF rules, SYN cookies, load testing, and traffic scrubbing
MITM
HTTPS with correct certificate validation, strong TLS, HSTS, secure DNS where appropriate, endpoint protection, and trusted network proxies
ARP spoofing
Dynamic ARP Inspection, 802.1X, port security, monitoring ARP changes, and static ARP entries for critical small systems
DNS attacks
DNSSEC validation, secure DNS configuration, endpoint monitoring, and application-layer certificate verification
Session hijacking
Secure cookies, short session lifetimes, token rotation, device binding, and reauthentication for sensitive actions
Credential theft
MFA, phishing-resistant authentication, rate limiting, credential monitoring, and user education
Detection tools include tcpdump, wireshark, Zeek, IDS systems, firewall logs, NetFlow data, and service-level metrics. For DNS investigations, dig can reveal suspicious responses; for connection state, ss is useful. For example, repeated SYN packets without completed connections may indicate a SYN flood, while unexpected changes in a host’s ARP cache can indicate ARP spoofing.
Real-World Considerations
Controls operate at different layers: TLS protects application data, IPsec protects IP packets, VLANs and physical controls limit local exposure, and firewalls filter traffic.
Encryption does not prevent every redirection attack: An attacker may still alter routing or ARP mappings. TLS detects many resulting impersonation attempts, but it does not repair the underlying network redirection.
Availability and security can conflict: Strict rate limits improve resilience but may block legitimate users. Security controls should therefore be monitored and tuned to expected traffic.
The human layer remains important: Phishing, stolen credentials, and MFA fatigue can bypass strong network defenses even when protocols are correctly configured.
71
How do symmetric and asymmetric encryption differ in networking?
KnownRevise
Symmetric encryption uses the same shared secret for encryption and decryption, while asymmetric encryption uses a mathematically related public-private key pair. Modern protocols such as TLS combine both: asymmetric cryptography establishes trust and shared session keys, and symmetric encryption efficiently protects the application data.
Read full answerHide full answer
Applies tocomputer networks (general concepts and TLS 1.3)
Core Difference
With symmetric encryption, both parties possess the same secret key:
The sender encrypts plaintext with the shared key.
The receiver decrypts the ciphertext with that same key.
Anyone who obtains the key can both encrypt and decrypt messages.
With asymmetric encryption, each party has a key pair:
The public key can be distributed openly.
The private key is kept secret.
Data encrypted with the public key can be decrypted with the corresponding private key, and signatures created with the private key can be verified with the public key.
The key sizes and algorithms must be compatible. For example, a key intended for AES cannot be used with an RSA or ECDH operation.
How They Are Used
Property
Symmetric encryption
Asymmetric encryption
Keys
One shared secret
Public-private key pair
Key distribution
Difficult and risky
Public key can be shared openly
Performance
Very fast
Much slower
Typical algorithms
AES-GCM, ChaCha20-Poly1305
RSA, ECDSA, ECDH, Ed25519
Typical data volume
Bulk or streaming data
Small payloads, signatures, or key establishment
Main risks
Key compromise exposes both directions
Private-key compromise; possible differences in padding or curve validation
Public-key cryptography is used for three related purposes:
Encryption: confidentiality for small data.
Digital signatures: integrity and authentication.
Key agreement: deriving a shared secret, such as with ECDH.
Key agreement is not itself encryption; for example, ECDH lets two parties derive a shared secret over an insecure channel.
Role in TLS
TLS 1.3 follows a hybrid encryption design:
The server proves its identity with a digital signature tied to a certificate from a trusted certificate authority.
The client and server perform an ephemeral key exchange, commonly using X25519 or a NIST elliptic curve.
They derive symmetric session keys using a key derivation function.
Application records are encrypted with an authenticated-encryption algorithm such as AES-GCM or ChaCha20-Poly1305.
TLS 1.3 does not use RSA key transport. It also uses ephemeral key exchange by default, providing forward secrecy: later compromise of the server’s long-term private key does not reveal previously recorded session traffic.
Trade-offs
Symmetric encryption is preferred for data encryption because it provides much higher throughput and lower CPU usage.
Asymmetric cryptography solves the key-distribution problem, but replacing symmetric encryption with it for bulk traffic would be inefficient.
Digital signatures are not encryption. A signature proves that a holder of the private key authorized a message; it does not conceal the message.
Hashing alone does not replace encryption or authentication. An unkeyed hash provides no protection against deliberate modification.
Asymmetric encryption does not automatically authenticate the peer. The exchanged public key must be validated through certificates, a previously pinned key, or another trusted mechanism.
In the textbook model, security is often shown as a service at the OSI presentation or application layer. Real networks implement security at several layers: TLS protects application sessions, IPsec protects IP packets, and link-layer protocols may provide separate wireless protections.
Best Practices and Pitfalls
Use authenticated encryption such as AES-GCM or ChaCha20-Poly1305; do not use unauthenticated modes such as AES-ECB.
Never reuse an encryption key and nonce pair with AES-GCM or the corresponding ChaCha20-Poly1305 construction.
Keep private keys protected, rotate them according to policy, and use appropriate algorithms such as ECDSA P-256 or Ed25519 for signatures.
Prefer ephemeral key exchange for forward secrecy rather than static RSA key transport.
Use a vetted protocol and library rather than designing a custom cryptographic protocol.
Remember that encryption provides confidentiality, while integrity and peer authentication require authenticated encryption, signatures, or both.
72
How do digital certificates and certificate authorities work?
KnownRevise
A digital certificate is a signed electronic document that binds a public key to an identity and associated permissions. A certificate authority (CA) is a trusted organization or system that verifies applicants and signs certificates, allowing relying parties to authenticate the holder of a private key.
Read full answerHide full answer
Applies toInternet PKI using X.509 v3 certificates and TLS 1.3
Core Concepts
Public-key cryptography solves an authentication problem: encrypting with a recipient’s public key does not prove who created the ciphertext. Certificates address this by having a trusted CA vouch for the association between a public key and an identity.
Component
Purpose
Digital certificate
Binds a public key to a subject name, domain, or other identity attributes
Certificate authority
Validates an applicant and signs the resulting certificate
Trust store
Contains trusted root certificates or public keys
Private key
Proves possession of the certificate’s corresponding public key; it is never stored in the certificate
Certificate chain
Connects an issued certificate to a recognized trust anchor
For example, a CA may verify control of www.example.com and issue a certificate containing that domain and the server’s public key. The server proves possession of the matching private key during the TLS handshake.
What an X.509 Certificate Contains
An X.509 v3 certificate contains core fields and may contain extensions:
Version and serial number: The version is 3; the serial number uniquely identifies the certificate within the issuer’s scope.
Signature algorithm and issuer: Identify the signing algorithm and the CA that issued the certificate.
Validity period: The dates before and after which the certificate is invalid.
Subject: Distinguished-name fields describing the subject; these may be empty when the SAN carries the identity.
Subject Public Key Info: Contains the public key and its algorithm.
Subject Alternative Name (SAN): Names and IP addresses covered by the certificate.
Key Usage: Optional permitted operations, such as digital signature or key encipherment.
Extended Key Usage: Optional intended purposes, such as TLS server authentication.
Basic Constraints: Indicates whether the certificate is a CA certificate and may specify a pathLenConstraint.
Authority Information Access (AIA): Optional URLs for the issuer’s certificate and OCSP responder.
CRL Distribution Points (CRLDP): Optional CRL locations; this is a separate extension from AIA.
The CA signs the DER-encoded TBSCertificate structure using the CA’s private key. A verifier uses the issuer’s public key to check that signature. The signature proves integrity and that the issuer signed the certificate; it does not independently prove the subject’s real-world identity. That assurance comes from the CA’s validation policy and the trust placed in it.
Certificate Issuance and TLS Validation
A typical public-CA issuance process is:
The applicant generates a key pair and creates a Certificate Signing Request (CSR) containing the requested identity and public key.
The CA validates the requested subject according to its policy: domain-validated certificates require domain-control checks, while organization- or individual-validated certificates require identity checks.
The CA creates the certificate and signs it with the CA private key.
The applicant installs the certificate and securely manages the corresponding private key.
During a typical full TLS 1.3 handshake, the server presents its certificate and related intermediate certificates. The client verifies the chain, hostname, key usages, and revocation status according to local policy, then uses the certificate’s public key to check the server’s CertificateVerify signature over the handshake transcript. Normal full handshakes use ephemeral (EC)DHE key exchange; PSK-only resumption need not present a certificate.
The root is normally the trust anchor. The server need not send the root because clients already trust it in their trust stores. A chain is valid only if every required signature, validity period, naming constraint, and usage condition is satisfied.
Revocation and Trust Management
A CA may revoke a certificate when the subject’s private key is compromised, the subject ceases to satisfy policy, or the issuer’s key is compromised.
Online Certificate Status Protocol (OCSP): Queries whether a specific certificate has been revoked.
Certificate Revocation List (CRL): A signed list of revoked certificate serial numbers.
OCSP stapling: Allows the server to provide a signed OCSP response during the handshake.
Certificate Transparency (CT): Public logs make the issuance of publicly trusted certificates more observable; they are not revocation lists.
Revocation is operationally difficult because clients must obtain and trust current status information, and some clients use a “soft-fail” policy when a responder is unavailable. Consequently, short-lived certificates, automated replacement, and certificate monitoring are increasingly important.
Security Considerations and Trade-offs
Self-signed certificates: Usable for internal systems, but clients must explicitly trust their public key or certificate. Self-signing alone provides no public trust.
Wildcard certificates: Match one label, such as *.example.com, but generally do not cover a.b.example.com or the bare example.com.
SAN validation: Modern clients validate hostnames against SAN, not only the older Common Name field.
Certificate pinning: Can reduce reliance on public CAs, but creates a serious availability risk when keys rotate unless backup pins and an update strategy are provided.
Private CAs: Give enterprises control over issuance, internal identities, and policy, but require secure key management and distribution of trust anchors.
Public CAs: Provide broad interoperability through globally distributed trust stores, but introduce issuance cost, validation delay, dependency on external infrastructure, and limited visibility into private organizational details.
The textbook model presents a clean hierarchy rooted in one trusted CA. Real systems are more complex: web browsers trust many roots; intermediates and cross-certificates connect ecosystems; name constraints restrict subordinate CAs; and private PKI deployments maintain separate organizational trust domains.
73
What is Wi-Fi, and how do IEEE 802.11 standards differ?
KnownRevise
Wi-Fi is a set of wireless LAN technologies that allows devices to exchange data over radio using the IEEE 802.11 standards. IEEE 802.11 defines the physical and MAC layers, while the Wi-Fi Alliance certifies compatible products and assigns familiar names such as Wi-Fi 6 and Wi-Fi 7.
Read full answerHide full answer
Applies tocomputer networks (IEEE 802.11 family through IEEE 802.11be-2024)
How Wi-Fi Works
Wi-Fi operates mainly at the physical layer and data link layer of the OSI model:
Physical layer: Transmits bits using radio frequencies and modulation schemes such as OFDM, DSSS, or QAM.
MAC layer: Controls access to the shared wireless channel, manages station discovery, association, frame acknowledgment, and retransmissions.
Upper layers: Carry ordinary IP traffic. TCP, UDP, HTTP, DNS, and other protocols operate above Wi-Fi without being aware of the wireless medium.
Unlike wired Ethernet, Wi-Fi normally uses CSMA/CA, not CSMA/CD. A transmitting station listens, waits for a random backoff period, transmits, and usually waits for an acknowledgment. RTS/CTS may be used to reduce collisions caused by hidden nodes.
How a Device Joins a Network
A typical connection proceeds as follows:
The client scans for access points broadcasting beacon frames containing an SSID and supported capabilities.
It selects a network and performs authentication and association with the access point.
WPA2 or WPA3 security keys are negotiated. Enterprise networks normally use 802.1X with EAP rather than a shared password.
The access point bridges frames between the wireless client and the wired network.
DHCP assigns an IP address, while DNS and the default gateway may be supplied by a home router or enterprise network.
The SSID identifies a logical WLAN, while the BSSID identifies a particular access-point radio interface.
Major 802.11 Standards
Standard
Frequency
Important advancement
Main trade-off
802.11a
5 GHz
OFDM modulation
Cleaner spectrum but shorter range
802.11b
2.4 GHz
DSSS modulation
Mature compatibility but low throughput
802.11g
2.4 GHz
OFDM in the 2.4 GHz band
Higher speed, but more interference susceptibility
802.11n
2.4 and 5 GHz
MIMO, wider channels, 40 MHz support
Wi-Fi 4; performance depends on client and interference
802.11ac
5 GHz
Wider channels and downlink MU-MIMO
Wi-Fi 5; excluded the 2.4 and 6 GHz bands
802.11ax
2.4, 5, and 6 GHz
OFDMA, uplink MU-MIMO, BSS coloring
Wi-Fi 6; improved efficiency in crowded environments
802.11be
2.4, 5, and 6 GHz
Multi-link operation, 320 MHz channels, 4K-QAM
Wi-Fi 7; higher throughput but greater hardware demands
Specialized variants include 802.11ah, which targets low-power, long-range IoT networks below 1 GHz, and 802.11ad, which uses the 60 GHz band for short-range, directional, high-rate links.
Standards are normally backward-compatible within their operating bands. However, a client’s actual speed is limited by the slowest negotiated link, radio conditions, channel width, antenna configuration, number of spatial streams, and contention from other stations.
Security and Practical Trade-offs
WPA3-Personal: Uses Simultaneous Authentication of Equals, or SAE, instead of the WPA2 pre-shared-key handshake.
WPA3-Enterprise: Uses 802.1X and EAP with stronger cryptographic options.
WPA2: Remains widely supported, but obsolete or poorly configured installations should be upgraded.
WEP and WPA: Obsolete and cryptographically insecure; they should not be used.
TLS: Protects sensitive application traffic such as HTTPS, but it does not replace WPA security because other traffic may remain unprotected.
The 2.4 GHz band usually provides better indoor range and wall penetration, although it is crowded and commonly uses only three non-overlapping 20 MHz channels. The 5 GHz band is generally faster and less congested. The 6 GHz band offers additional clean spectrum and wider channels, but its shorter effective range makes it more appropriate for dense deployments.
Real-World Differences and Diagnostics
A textbook access point mainly bridges wireless and wired frames. Real consumer routers usually combine that role with DHCP, DNS forwarding, firewalling, and NAT; enterprise deployments may use controllers and tunnel the traffic across a switched network.
Troubleshooting should follow the network layers:
Use iw dev wlan0 scan to inspect nearby access points.
Use ip addr and ip route to verify addressing and the default route.
Use ss to inspect TCP or UDP connections.
Use dig to test DNS and curl to test HTTP or TLS.
Use ping for basic reachability and tcpdump to inspect actual packets.
A client may show a valid Wi-Fi association but still be unable to reach the internet if DHCP, DNS, routing, authentication, or the access point’s upstream connection is faulty.
74
What are the security differences between WPA2 and WPA3?
KnownRevise
WPA2 and WPA3 are Wi-Fi security standards built on IEEE 802.11i. WPA3 strengthens authentication and management-frame protection; for WPA3-Personal, it replaces WPA2-PSK’s four-way handshake with SAE, while WPA3-Enterprise retains 802.1X/EAP and can use stronger cipher suites.
Read full answerHide full answer
Applies toIEEE 802.11i, WPA2, WPA3, and Wi-Fi Protected Access standards
Key Differences
Aspect
WPA2
WPA3
Personal-network authentication
Pre-Shared Key (PSK) based on a four-way handshake
Simultaneous Authentication of Equals (SAE), based on the Dragonfly key exchange
Password resistance
Vulnerable to offline dictionary attacks if the handshake is captured
Resistant to simple offline dictionary attacks; password is not transmitted directly
Encryption
Commonly uses AES-CCMP; TKIP is legacy
Uses modern authenticated-encryption suites, including GCMP; WPA3-Enterprise 192-bit mode uses GCMP-256
Enterprise authentication
Uses 802.1X/EAP with an authentication server
Retains 802.1X/EAP, with stronger suite options and optional 192-bit security
WPA3-only networks exclude WPA2-only clients; transition mode supports both
WPA2 Personal Authentication
In WPA2-Personal, a user enters a shared passphrase. The access point and client perform a four-way handshake to derive session keys. The passphrase itself is not sent over the air, but the handshake contains enough material for an attacker to test password guesses offline.
WPA2-Personal typically derives the Pre-Shared Key from the passphrase and network name using PBKDF2-HMAC-SHA1, with 4096 iterations in the standard. This slows guessing, but a weak password can still be recovered relatively quickly on modern hardware. WPA2-Enterprise avoids this shared-password model by using 802.1X, an EAP method, and a RADIUS server.
WPA3 Personal Authentication
WPA3-Personal replaces the PSK handshake with SAE, based on the Dragonfly key exchange. SAE uses a password-authenticated key exchange: the client proves knowledge of the password without transmitting a value that directly reveals it.
This makes an ordinary captured WPA3-Personal handshake substantially less useful for an offline dictionary attack. It also helps protect against downgrade attacks, where an attacker tries to force a WPA3-capable device to use weaker WPA2-style authentication.
SAE improves password security, but it does not make a weak password strong. A short or commonly used passphrase can still be guessed through online attempts or other practical attacks.
WPA3/WPA2 transition mode: Allows WPA3 and WPA2 clients to use the same SSID and password. It is intended as a temporary migration mechanism.
WPA3-Enterprise: Uses 802.1X/EAP and can support stronger cipher suites.
WPA3-Enterprise 192-bit mode: Uses stronger cryptographic suites such as GCMP-256 and generally requires appropriate server certificates and client configuration.
Transition mode is not equivalent to WPA2 security everywhere: a WPA2-capable client connecting to a transition network may still receive the older authentication behavior. It should be removed after legacy devices are replaced or isolated.
Practical Example
Suppose a home network currently uses WPA2-Personal. Migrating to WPA3-Personal improves resistance to captured-handshake password attacks. However, an old printer that supports only WPA2 cannot join the WPA3-only network.
A practical migration is:
Create a WPA3/WPA2 transition SSID.
Upgrade laptops, phones, and other important clients.
Move remaining WPA2-only devices to a separate, isolated network.
Disable transition mode once migration is complete.
In Linux systems, hostapd and wpa_supplicant provide the relevant AP and client support. Enterprise deployments must also configure the RADIUS server and certificate or credential requirements correctly.
Security Trade-Offs and Best Practices
Use a long, unique passphrase; WPA3 does not eliminate the need for strong credentials.
Prefer WPA3-Personal or WPA3-Enterprise when all devices support them.
Treat WPA3 transition mode as temporary, not as the permanent security target.
Avoid WPS, TKIP, and obsolete firmware because they weaken the wireless security posture.
Keep access-point firmware, hostapd, and wpa_supplicant updated.
Use WPA3-Enterprise 192-bit mode only when clients, the RADIUS server, certificates, and network infrastructure support its stronger requirements.
75
What is the definition of software-defined networking (SDN)?
KnownRevise
Software-defined networking (SDN) is a network architecture that separates network control decisions from packet forwarding, allowing forwarding and network policies to be programmed and managed through software rather than configured independently on every device.
Read full answerHide full answer
Applies tosoftware-defined networking (SDN) concepts; OpenFlow 1.3 where OpenFlow-specific behavior is mentioned
Key Components
Control plane: The part of the network that maintains network state and determines forwarding policy. It may run on one controller or on a distributed controller cluster.
Data plane: Forwarding devices such as switches and routers that match packets against forwarding tables and execute actions such as forwarding, modifying, or dropping traffic.
Southbound interface: The interface between controllers and network devices. OpenFlow 1.3 is a common example; NETCONF and OVSDB are other examples used by some platforms.
Northbound interface: An interface through which applications, orchestrators, and operators interact with the controller. There is no single universally adopted northbound API.
Network operating system: Software that provides network abstractions and services, commonly associated with controller platforms such as OpenDaylight and ONOS.
How It Works
The controller or its applications discover devices, links, ports, and other topology information through mechanisms such as LLDP.
An application or administrator supplies a network policy through a northbound interface.
The controller or a network application translates that policy into forwarding state.
The controller installs flow entries through the southbound interface.
When a packet arrives, a device matches it against one or more flow tables and applies the associated actions. Flow tables may be implemented with TCAM, hash-based lookup, or other hardware mechanisms.
If no entry matches, behavior depends on the configured table-miss action. The device may drop the packet, use another table, or send a packet-in message to the controller.
For example, an administrator can define a new traffic policy centrally and have the controller update the affected switches rather than manually changing each device.
Comparison with Traditional Networking
Aspect
Traditional networking
SDN
Control plane
Usually distributed across devices
Often logically centralized, but may be implemented as a distributed cluster
Configuration
Often performed per device through CLIs or automation
Commonly based on policy expressed through controllers or orchestration systems
Flexibility
Depends on each device’s platform and features
Programmable behavior is possible where the hardware and interfaces support it
Visibility
Often centered on per-device state
May provide a broader, shared network view
Scaling and failure
Distributed routing protocols are designed to scale and tolerate device failures
Controller capacity and availability must be considered; redundancy is important
Vendor dependence
Frequently high
Can reduce dependence when standards and compatible hardware are used
Advantages and Limitations
Agility (advantage): Centralized policy can make network changes faster than manual configuration of many devices.
Programmability (advantage): Applications can automate routing, service chaining, traffic engineering, and policy enforcement.
Consistent management (advantage): A controller can apply common policies across supported devices, although implementations may still differ.
Cost (advantage): Commodity white-box switches can reduce hardware costs, but savings depend on operational and licensing costs.
Controller scalability (limitation): Large deployments require sufficient controller throughput, clustering, and appropriate placement.
Availability (limitation): Loss of the controller plane can prevent new flows from being installed; existing behavior depends on the forwarding devices and platform design.
Control-channel security (limitation): Controller-to-device communication requires authentication, encryption where supported, and protection against unauthorized rule installation.
Complexity and lock-in (limitation): Controllers, applications, hardware support, and orchestration systems can create integration dependencies despite the use of open interfaces.
Real-World Use Cases
Data-center fabrics: Hyperscalers use programmable fabrics and centrally managed routing policies to support large-scale, resilient networks.
Wide-area networks: Networks such as Google’s B4 use SDN principles to program traffic paths across a global WAN.
SD-WAN: Many SD-WAN products use a logically centralized controller to select paths among transports such as broadband, MPLS, and cellular links. SD-WAN is a distinct technology that may use APIs other than OpenFlow.
Security: SDN applications can implement microsegmentation and dynamic policy, but SDN alone does not provide zero-trust security or a software-defined perimeter.
Campus networks: Some campuses use centrally programmed policies for mobility, authentication, and traffic management.
Best Practices and Common Pitfalls
Deploy redundant controllers: Use controller clustering and, where supported, consensus or leader election to maintain availability.
Secure the control channel: Use authenticated TLS or the platform’s supported secure transport, and restrict access to controller management interfaces.
Keep abstractions layered: Expose stable northbound services rather than coupling applications to low-level flow-table details.
Monitor the control plane: Track flow-installation latency, packet-in rates, controller CPU and memory use, and rule-table capacity.
Design for hardware limits: Flow tables can exhaust TCAM or forwarding-ASIC resources; account for match complexity, timeout behavior, and the platform’s group and meter capabilities.
Test failure behavior: Verify whether traffic continues when a controller, southbound link, application, or individual switch fails.
76
What is the difference between WebSocket and HTTP connections?
KnownRevise
WebSocket is a persistent, full-duplex application protocol in which a client and server can exchange messages independently. HTTP, by comparison, is primarily a client-initiated request-response protocol, although HTTP/2 and HTTP/3 multiplex independent streams and HTTP can deliver one-way server updates using mechanisms such as Server-Sent Events.
Read full answerHide full answer
Applies toWebSocket protocol version 13 (RFC 6455), WebSocket over HTTP/2 (RFC 8441), HTTP/1.1 (RFC 9112), HTTP/2 (RFC 9113), and HTTP/3 (RFC 9114)
How HTTP Works
A client starts an HTTP exchange by sending a method, target, headers, and an optional body. The server returns a status, headers, and an optional response body.
HTTP/1.1 connections are persistent by default, allowing multiple requests to reuse one TCP connection. Its application-level exchange remains request-response.
HTTP/2 multiplexes independent request streams over one TCP connection, while HTTP/3 multiplexes them over a QUIC connection. Both permit simultaneous transmission in both directions on a stream, but apart from HTTP/2 and HTTP/3 server push (rarely used today and removed from major browsers), each stream starts with a client request.
A server can send unsolicited updates over HTTP using Server-Sent Events or long polling. Server-Sent Events are one-way, however; they do not provide the symmetric message exchange of WebSocket.
How WebSocket Works
Traditional WebSocket uses an HTTP/1.1 handshake: the client sends an Upgrade: websocket request, and the server accepts it with 101 Switching Protocols. The existing TCP connection then carries WebSocket frames instead of ordinary HTTP exchanges.
WebSocket frames can carry text, binary data, control frames such as ping and pong, and close notifications. Both endpoints may send frames without waiting for the other endpoint to initiate a request.
RFC 6455 requires client-to-server frames to be masked. Its base frame header is 2–10 bytes depending on payload length, with an additional four-byte mask on client-to-server frames.
WebSocket over HTTP/2 instead uses HTTP/2’s extended CONNECT mechanism under RFC 8441, so it does not use the HTTP/1.1 101 upgrade.
An established WebSocket can end through an application close handshake, but it can also terminate because of network failure, an idle timeout, server shutdown, or a protocol error.
Key Differences
Aspect
HTTP
WebSocket
Communication pattern
The client initiates each request; responses and SSE streams follow that request
Both endpoints can send messages independently
Transport
HTTP/1.1 and HTTP/2 use TCP; HTTP/3 uses QUIC over UDP
Traditional WebSocket uses TCP; WebSocket over HTTP/2 uses an HTTP/2 stream
Connection use
HTTP/1.1 can reuse a connection; HTTP/2 and HTTP/3 multiplex streams
A traditional WebSocket normally has one persistent connection and one logical session
Framing overhead
HTTP/1.1 repeats textual headers; HTTP/2 and HTTP/3 compress headers using HPACK and QPACK
Compact binary frames, with client-to-server masking
Server-initiated data
Available through SSE or long polling, generally one-way
Chat, collaborative editing, notifications, and other frequent bidirectional events
Advantages and Trade-offs
WebSocket advantages: It removes repeated polling, reduces protocol overhead for frequent small messages, and lets a server send updates immediately. It is well suited to interactive applications that need both real-time delivery and client-originated events.
HTTP advantages: HTTP has mature caching, compression, proxy, CDN, observability, and authorization ecosystems. For ordinary request-response operations, persistent WebSocket connections can add unnecessary state and resource usage.
WebSocket complexity: Long-lived connections require heartbeat mechanisms, reconnect handling, backpressure, connection limits, and state coordination when servers are replicated. A shared load balancer may also require sticky routing or external session and message infrastructure.
Comparison caveat: WebSocket is not automatically lower-latency or more efficient than every modern HTTP implementation. HTTP/2 and HTTP/3 already provide multiplexed, persistent connections, while WebSocket’s main advantage is its symmetric message-oriented application model.
Security and Operational Considerations
Use wss:// in production so WebSocket traffic is protected by TLS. The ws:// scheme is unencrypted.
Browsers include an Origin header in the WebSocket handshake. The server must validate it against an allowlist; the browser’s same-origin policy does not automatically prevent every cross-origin WebSocket connection.
Cookie-based authentication can expose a WebSocket endpoint to cross-site request-forgery attacks. Combine strict Origin validation with appropriate CSRF controls and SameSite cookie settings.
Non-browser clients can send an Authorization header during the handshake, but the native browser WebSocket API cannot set arbitrary headers. Browser applications normally use a secure cookie or an application-specific authentication mechanism.
Use protocol-level ping/pong heartbeats to detect broken peers, and authenticate and authorize messages as well as the initial connection.
77
How to troubleshoot a computer with no internet access?
KnownRevise
Use layer-by-layer troubleshooting to isolate the failure: verify the physical connection, local IP configuration, routing, external reachability, DNS, and finally the application or transport connection. Each layer depends on the previous one, so changing multiple settings simultaneously makes the root cause harder to identify.
Read full answerHide full answer
Applies tocomputer networking (TCP/IP with IPv4 examples; Linux and Windows command-line tools)
Troubleshooting Model
The OSI and TCP/IP models provide a useful diagnostic order. In real systems, the boundaries are not always strict—for example, DNS and DHCP use UDP, IP, and Ethernet together—but the dependency remains.
Layer
What to verify
Typical symptoms
Physical
Cable, Wi-Fi signal, interface state, link speed
No carrier, disconnected network
Data link
Ethernet/Wi-Fi connectivity, ARP resolution
Gateway is unreachable despite a configured address
Network
IP address, subnet mask, default gateway, route
Local network works, but external IP does not
Transport
TCP/UDP connectivity, firewall rules
Host resolves but connections time out
Application
DNS, HTTP, TLS, proxy, service availability
Website fails while other internet traffic works
A failure at one layer usually prevents higher layers from functioning correctly.
Layer-by-Step Checks
Confirm the interface is connected
Check Wi-Fi, Ethernet cables, docking stations, and router ports.
On Linux, inspect ip link for the administrative state and flags such as NO-CARRIER. An UP state alone does not prove that the physical link is usable.
A computer may be associated with Wi-Fi but have no DHCP lease.
Validate the IP configuration
Confirm that the interface has an address from the expected subnet.
Verify the subnet prefix is correct; for example, 192.168.1.42/24 belongs to 192.168.1.0/24.
Check whether DHCP assigned the configuration or whether a static address is required.
Test loopback with ping 127.0.0.1.
Check the default route
The computer needs a default route to reach networks outside its subnet.
Ping the default gateway first when ICMP is permitted. A failure can indicate a local network, VLAN, Wi-Fi, or gateway problem, but it can also result from ICMP filtering.
If the gateway is reachable but an external IP is not, investigate routing, ISP connectivity, or firewall filtering.
Separate DNS from general connectivity
Ping a numeric IP address such as 1.1.1.1. If it works but a hostname fails, DNS is the likely problem.
Check /etc/resolv.conf, DHCP-provided DNS settings, VPN DNS configuration, and DNS filtering.
Remember that a failed ping alone does not prove the computer is offline; many firewalls and servers block ICMP.
Test the transport and application
Check whether TCP port 443 is reachable.
Inspect proxy settings, VPN routes, host firewalls, and DNS-over-HTTPS behavior.
For HTTPS, distinguish connection failure from certificate validation failure, expired certificates, and incorrect system time.
For IPv6-only paths, repeat relevant checks with ip -6 route, ping -6, dig AAAA, and curl -6.
Worked Example
Suppose a Linux computer has 192.168.1.42/24, with 192.168.1.1 as its gateway:
The gateway responds to ping: Wi-Fi, Ethernet, IP configuration, and local routing are probably working.
ping 1.1.1.1 fails: investigate the default route, router uplink, ISP failure, VPN policy, outbound firewall rules, or ICMP filtering.
ping 1.1.1.1 succeeds, but dig example.com fails: troubleshoot DNS rather than general network connectivity.
DNS resolves, but HTTPS fails: inspect proxy settings, port 443 filtering, TLS certificates, and the destination service.
Code Example
The following Linux commands isolate the main dependencies. Run them individually as needed rather than as an automated script.
# Interface state and IP addresses
ip link
ip -br addr
# Default route and ARP neighbor information
ip route
ip neigh
# Identify an IPv4 gateway selected by the current routing table
GATEWAY=$(ip -4 route show default | awk '$2 == "via" {print $3; exit}')
if [ -n "$GATEWAY" ]; then
ping -c 3 "$GATEWAY"
else
echo "No IPv4 default route with a gateway"
fi
# Test loopback, a public IP, and DNS separately
ping -c 3 127.0.0.1
ping -c 3 1.1.1.1
dig +short example.com
# Test HTTPS, inspect listeners, and trace the route
curl --connect-timeout 10 -I https://example.com
ss -tulpn
traceroute 1.1.1.1
# Optional packet capture; run with sufficient privileges
tcpdump -ni any port 443
On Windows, use ipconfig /all, route print, nslookup, and Test-NetConnection example.com -Port 443 for equivalent checks.
Best Practices and Common Pitfalls
Change one variable at a time: Otherwise, it becomes unclear which action restored connectivity.
Test each boundary: Gateway, external IP, hostname, and application port provide progressively narrower fault domains.
Do not disable the firewall permanently: Identify the blocked traffic and create a narrowly scoped rule if necessary.
Check active VPNs: VPN clients can replace default routes, DNS servers, and proxy settings.
Use packet captures carefully: Captures may expose credentials or sensitive application data.
Record evidence: Save command output, timestamps, interface details, and traceroute results before rebooting or changing configuration.
78
How to diagnose high latency between two servers?
KnownRevise
High latency between two servers is diagnosed by separating network-path delay from delay caused by DNS, TLS, the application, or the destination host. The primary network signal is round-trip time (RTT), but it must be compared with end-to-end application timings under a repeatable baseline.
Read full answerHide full answer
Applies tocomputer networks (general concepts and Linux diagnostics)
Establish the Baseline
Scope: Identify affected endpoints, directions, services, ports, and time periods. Determine whether the issue affects one source, one destination, or only a particular application.
Pattern: Record whether latency is consistent, intermittent, correlated with traffic, or accompanied by packet loss, jitter, retransmissions, CPU saturation, or growing queues.
Comparison: Test during normal and degraded periods rather than relying on a single ping result. A single sample can be distorted by transient congestion or ICMP handling.
Server traces, database timings, CPU and queue metrics
TLS/DNS
Slow resolver, DNS retries, expensive TLS handshake
Resolver response time, DNS logs, handshake timing
Transport
TCP retransmissions or congestion; TCP zero-window stalls; UDP loss
ss -tin, packet captures, TCP statistics
Network/IP
Congestion, routing changes, MTU black holes causing retransmission
traceroute, mtr, hop-by-hop RTT
Link
Errors, speed or duplex mismatch, overloaded NIC
Interface counters, negotiated speed, ethtool
This resembles the OSI-style layering used in textbooks, although real TCP/IP stacks combine several OSI layers and Linux exposes their measurements through different tools.
Separate the Path from the Application
Ping: Measures ICMP RTT and packet loss. It does not represent HTTP, database, or other application latency.
Traceroute: Shows possible latency increases between hops. Middleboxes can hide the forwarding path, and different hops may respond to the probe protocol differently.
MTR: Combines repeated traceroute measurements with loss statistics, which helps reveal intermittent congestion.
DNS timing: Check whether name resolution is slow or repeatedly retried.
TLS timing: Compare the cumulative TLS milestone with DNS and TCP milestones.
First-byte timing: Measure the interval between the start of the request and receipt of its first byte. Use server traces to determine how much of that interval was server processing rather than network delay.
With synchronized clocks and bounded clock error, one-way delay can be measured directly. Otherwise, RTT / 2 is only an approximation and is unreliable when the forward and reverse paths differ.
Worked Example
Suppose the observations are:
ICMP RTT to the destination: 12 ms
RTT to an intermediate router: 3 ms
Cumulative curl milestones:
DNS lookup: 4 ms
TCP connected: 12 ms
TLS established: 32 ms
First byte received: 102 ms
Request completed: 102 ms
The individual phases are therefore:
DNS: 4 ms
TCP setup: 12 - 4 = 8 ms
TLS handshake: 32 - 12 = 20 ms
Request-to-first-byte wait: 102 - 32 = 70 ms
The dominant delay occurs after TLS establishment, so investigation should focus on request processing, server resources, downstream database calls, locks, and application logs. The low ICMP RTT does not by itself exclude packet loss or TCP retransmissions.
If mtr shows the destination hop rising from 12 ms to 80 ms, that is a useful clue, not proof. The final segment, destination host, uplink, or ICMP prioritization at the destination could produce the observation.
Code Example
These Linux commands provide an initial comparison:
TARGET="server.example.com"
# Measure ICMP RTT and loss over multiple samples
ping -c 20 "$TARGET"
# Trace a TCP path toward port 443
traceroute -T -p 443 "$TARGET"
# Sample hop latency and loss over time
mtr -r -w -c 100 "$TARGET"
# Inspect DNS resolution
dig "$TARGET"
# Print cumulative connection milestones
curl -sS -o /dev/null \
--connect-timeout 5 --max-time 30 \
-w 'dns=%{time_namelookup}s connect=%{time_connect}s tls=%{time_appconnect}s first_byte=%{time_starttransfer}s total=%{time_total}s\n' \
"https://$TARGET"
# Inspect active TCP connections and retransmission counters
ss -tin
# Capture up to 100 TCP packets involving the destination
DEST_IP="203.0.113.10" # Replace with the actual destination address
sudo timeout 30s tcpdump -ni any -c 100 "host $DEST_IP and tcp port 443"
Best Practices and Common Pitfalls
Compare application timing with ICMP RTT; fast ping results do not exclude slow DNS, TLS, or application processing.
Do not assume traceroute shows the actual packet path; ECMP, firewalls, and ICMP rate limiting can distort it.
Treat intermediate-hop measurements as clues rather than definitive proof of router failure.
Monitor packet loss and retransmissions because TCP loss recovery can sharply increase latency.
Check both endpoints for CPU throttling, NIC queues, soft interrupts, memory pressure, and connection-backlog exhaustion.
Capture traffic on both endpoints when possible; one side may miss losses on the return path.
Compare multiple destinations, sources, ports, and times to isolate a network, host, or service-level fault.
79
How does a packet travel from a laptop to a server across the Internet?
KnownRevise
A packet reaches a distant server through hop-by-hop forwarding: the laptop sends it to its local router, and each router forwards it toward the next network until it reaches the destination network. The complete path is selected through routing protocols, while individual routers only choose the next hop.
Read full answerHide full answer
Applies tocomputer networks (TCP/IP and OSI models)
The Network Journey
A request typically follows this path:
Name resolution: The application resolves a hostname such as example.com into an IP address using DNS.
Local delivery: The laptop sends the packet to its default gateway, normally the home or office router.
Private-to-public translation: If the laptop uses a private address, the router performs Network Address Translation (NAT), replacing the private source address with a public address.
Internet routing: ISP routers examine the destination IP address and forward the packet through provider networks.
Internet exchange: Traffic may pass through an Internet Exchange Point (IXP), where networks connect and exchange traffic directly.
Destination delivery: The server’s network removes any remaining NAT mapping and forwards the packet to the server.
Response: The server sends a reply through the routing system, and the client’s NAT reverses the translation.
Each physical link is independent. A packet might cross Wi-Fi, fiber, Ethernet, and different ISP networks before reaching the server.
Encapsulation Through the Layers
Data is wrapped as it moves down the sender’s protocol stack and unwrapped as it moves up the receiver’s stack.
TCP/IP layer
OSI equivalent
Examples
Main responsibility
Application
Application, Presentation, Session
HTTP, DNS, SMTP, TLS
Exchange application data
Transport
Transport
TCP, UDP
Ports, reliability, flow control, congestion control
Internet
Network
IPv4, IPv6, ICMP
Logical addressing and routing
Network access
Data link, Physical
Ethernet, Wi-Fi, PPP
Frames, media access, physical transmission
At the sender, an HTTP request becomes TCP segments containing IP packets and then link-layer frames. Each router removes the old frame, checks the IP destination, selects a new outgoing interface, and creates a new frame for the next link.
How Routers Choose the Next Hop
Routers use routing tables populated through protocols such as RIP, OSPF, and BGP. For a destination address, they normally use longest-prefix matching: the most specific matching route wins. A route such as 203.0.113.0/26 is preferred over a broader route such as 203.0.0.0/16.
At the local network, the laptop first determines the router’s MAC address using ARP on IPv4 or Neighbor Discovery on IPv6. It then sends the Ethernet frame to that router. At every subsequent hop:
The router checks the destination IP address.
It decreases the IPv4 Time-to-Live (TTL) value or IPv6 Hop Limit.
It selects an outgoing interface and next hop.
It replaces the link-layer frame header.
It forwards the packet asynchronously; routers do not wait for the whole journey to finish.
Routing decisions can change during the trip, so different packets of the same TCP connection may follow slightly different paths.
A Concrete Example
Suppose the laptop has private address 192.168.1.24 and wants to contact a server at 93.184.216.34:
The laptop sends the packet to its gateway, such as 192.168.1.1.
The gateway performs NAT and forwards it into the ISP network.
ISP routers forward it through several backbones and possibly an IXP.
The destination ISP routes it to the server’s network.
The server receives the packet and replies to the public address associated with the NAT mapping.
The gateway translates the reply back to 192.168.1.24 and delivers it locally.
The original IP destination generally remains unchanged across the Internet. NAT changes the source address at the network edge, while lower-layer headers are repeatedly replaced at each physical hop.
Reliability, Security, and Real-World Differences
TCP establishes a connection with a handshake, numbers segments, retransmits missing data, and regulates transmission using congestion control.
UDP does not provide these guarantees, making it suitable for real-time or request-response workloads.
TLS encrypts application data after establishing the transport connection. It protects confidentiality and integrity but does not hide all network metadata.
ICMP carries diagnostics such as ping messages and reports errors such as unreachable destinations.
In the textbook model, packet loss and delay may occur on every segment of a path. Real Internet paths are dynamic and heterogeneous, with variable bandwidth, queueing delay, loss, and possible route changes.
Routers generally do not fragment IPv4 packets; endpoints use Path MTU Discovery. IPv6 routers never fragment packets.
Useful command-line tools include dig for DNS resolution, traceroute for observing hops, ping for reachability and round-trip time, tcpdump for packet inspection, and ss for examining local TCP or UDP connections.
80
TCP keep-alive vs HTTP keep-alive: what's the difference?
KnownRevise
TCP keep-alive is an optional transport mechanism that probes an idle TCP connection to detect an unresponsive peer. HTTP keep-alive, more accurately called an HTTP persistent connection, reuses one TCP connection for multiple HTTP request-response exchanges; it primarily reduces connection-establishment overhead rather than detecting a dead peer.
Read full answerHide full answer
Applies toall TCP implementations (RFC 1122 requirements and RFC 9293), HTTP/1.1 (RFC 9110 and RFC 9112), and historical HTTP/1.0 persistent connections
What Each Mechanism Does
Aspect
TCP Keep-Alive
HTTP Keep-Alive
OSI layer
Transport layer, Layer 4
Application layer, Layer 7
Primary purpose
Detect an unresponsive peer on an otherwise idle TCP connection
Reuse a TCP connection for multiple HTTP exchanges
Traffic sent
TCP keep-alive probe segments
HTTP requests and responses
Activation
Usually enabled explicitly by the application through a socket option
Persistent by default in HTTP/1.1
Liveness detection
Provides eventual detection for an idle, broken TCP path
Provides no liveness guarantee; a broken connection is discovered when it is next used
Connection setup savings
None
Avoids repeated TCP handshakes and transport-layer setup
How TCP Keep-Alive Works
An application normally enables TCP keep-alive through the SO_KEEPALIVE socket option. After a configured idle period, the TCP stack sends a probe segment intended to make the peer return an acknowledgment. If the peer responds, the connection remains active; if a configured number of consecutive probes go unanswered, the TCP stack closes the connection.
The idle duration, probe interval, and failure threshold are implementation-specific. For example, Linux exposes TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT; values such as 7200 seconds, 75 seconds, and three probes should not be presented as universal TCP defaults. TCP keep-alive is also distinct from retransmission: retransmission handles suspected loss of transmitted data, whereas keep-alive checks an otherwise silent connection.
Keep-alive traffic may prevent some NAT gateways or stateful firewalls from expiring a mapping, but this depends on the middlebox and is not guaranteed. It also cannot detect an application-level hang if the application continues sending TCP data or immediately responds to probes. SSH, for example, commonly implements its own application-layer keepalive mechanism rather than relying only on TCP keep-alive.
How HTTP Keep-Alive Works
In HTTP/1.1, a TCP connection is persistent by default, allowing a client to send another request after receiving the previous response without opening another TCP connection. Either party may close the connection, and Connection: close explicitly requests closure after the current exchange. Historical HTTP/1.0 required opt-in persistence, commonly through Connection: keep-alive.
The server’s idle-connection timeout is an implementation policy, not an HTTP protocol default. A server may advertise values such as Keep-Alive: timeout=5, max=100, but such values are advisory and do not guarantee that the server closes the connection at exactly that time. Clients must therefore handle a persistent connection closing between requests and may retry eligible requests when doing so is safe.
HTTP/1.1 pipelining can place multiple requests on one connection without waiting for each response, but it causes head-of-line blocking and is rarely used by modern clients.
Concrete Example
Suppose a browser downloads an HTML page, a stylesheet, and an image from the same origin. HTTP keep-alive lets all three HTTP exchanges use one TCP connection, avoiding two additional TCP handshakes. If that connection then remains idle, enabled TCP keep-alive may send TCP probes to determine whether the peer or path is still reachable. HTTP keep-alive itself does not send those probes or guarantee that the connection is alive.
Practical Guidance and Protocol Evolution
Use TCP keep-alive as a transport-level backstop for long-lived connections, while choosing an idle period that detects failures reasonably quickly without generating excessive probe traffic.
Use application heartbeats when liveness depends on application progress; TCP can remain healthy while the application is stuck.
Configure sensible HTTP idle timeouts and connection limits because persistent connections save handshakes but can occupy server sockets and file descriptors.
HTTP/2 multiplexes streams over one TCP connection, so HTTP/1.1-style request reuse is less relevant, although TCP keep-alive may still operate underneath it. HTTP/3 runs over QUIC on UDP, so TCP keep-alive is replaced by QUIC-level keepalive behavior.