TDEB Top Bar

Trending
Semiconductor Industry News — The Digital Electronics Blog
Follow Us

TDEB Masthead

The Semiconductor Hub

Semiconductors.  Chips and Systems.  Innovation.

Indexed by leading Search Engines, AI and referenced by Engineers worldwide 500+ Articles 10M+ Pageviews 30+ Reports 50+ Citations

TCP Interview Questions and Answers

The Editor's Desk
by
0
Share Facebook X LinkedIn WhatsApp Email

TCP comes up in almost every interview for networking, embedded and SoC roles that touch Ethernet or a modem stack. This post answers the classic questions in plain words first: what TCP is, how it avoids choking the network, how ports work, what a socket is, and how you tell that the far end has died. The second half has the numbers: header fields, timers, congestion window rules and keepalive settings, with the RFC section for each.

The question list follows the old comp.protocols.tcp-ip FAQ maintained by Mike Oliver (part 1 and part 2, version of September 1999, archived copies). The answers below are summaries in our own words, updated to the current RFCs.

What is TCP?

Transmission Control Protocol (TCP) gives two programs a reliable, ordered stream of bytes between them across an IP network. IP itself makes no promises: packets can be lost, corrupted, duplicated or delivered out of order. TCP hides all of that. It numbers every byte it sends, adds a checksum, and expects the receiver to acknowledge what arrived. Anything not acknowledged in time is sent again, and the receiver puts the bytes back in order before handing them to the application.

TCP is connection oriented. Before any data moves, the two ends exchange a short set of control segments to agree on starting sequence numbers (the three-way handshake). When the application is done, another exchange closes the connection. In OSI terms it is a connection-oriented, acknowledged transport.

TCP also controls how fast it sends. Flow control stops a fast sender from overrunning a slow receiver, and congestion control stops all senders together from overloading the routers in between. To use the network efficiently it tries to fill each IP packet with as much data as it can, although an application that cares more about latency than efficiency can turn that batching off.

The base protocol was defined in RFC 793 (1981). RFC 1122 collected the corrections and requirements for hosts as of October 1989. Today the single current specification is RFC 9293, published in August 2022, which obsoletes RFC 793 and several smaller RFCs. New features must stay backward compatible: a TCP that supports a new option still has to work with one that does not.

How does TCP avoid network meltdown?

If every sender pushed data as fast as its link allowed, router queues would overflow, packets would be dropped, senders would retransmit, and the network would fill with copies of the same data. This is congestion collapse, and the early Internet suffered it in October 1986. Van Jacobson and Michael Karels describe the episode in Congestion Avoidance and Control (1988): throughput between two sites about 400 yards apart fell from 32 kbps to 40 bps.

Their fix, now part of every TCP, is a set of four algorithms:

  • Slow start: a new connection begins with a small window and grows it quickly while acknowledgments keep coming back.
  • Congestion avoidance: once the window reaches a threshold, it grows slowly, about one segment per round trip.
  • Fast retransmit: repeated duplicate acknowledgments signal a lost segment, which is resent without waiting for a timer.
  • Fast recovery: after a fast retransmit the sender halves its rate instead of dropping back to slow start.

These were first written up together in RFC 2001 (1997); the current version is RFC 5681 (2009). Two older rules also keep traffic sensible. Silly window syndrome avoidance, from RFC 813, stops the two ends from trading tiny windows and tiny segments. The Nagle algorithm, from RFC 896, stops a sender from flooding the network with a train of small packets by holding back new small segments while earlier data is still unacknowledged.

The original FAQ also pointed to a paper by Sally Floyd on recovering quickly from packet loss. Its old FTP location no longer exists, so it is not linked here.

How do applications share TCP and UDP?

Each application using TCP or UDP is identified by a 16-bit port number. The sender puts a source port and a destination port in every TCP or UDP header, and the receiving host uses the destination port to hand the data to the right program. A single server can run Telnet on TCP port 23, FTP on TCP port 21 and DNS on port 53 at the same time. UDP has its own separate set of port numbers.

Servers like these listen on well-known ports. The numbers themselves are arbitrary; they are fixed by tradition and by official assignment from the Internet Assigned Numbers Authority (IANA).

Where do I find assigned port numbers?

For years IANA published its assignments as a periodic "Assigned Numbers" RFC; the last was RFC 1700. RFC 3232 (January 2002) retired that series and replaced it with an online database. Port numbers now live in the IANA Service Name and Transport Protocol Port Number Registry.

What are sockets?

A socket is the programming handle for one end of a communication. Most programs that use TCP or UDP create a socket of the right type and then perform operations on it. Those fall into three groups: control (bind a port, connect, accept, close), data transfer (send and receive) and status (for example, look up the local or remote address). The full set is the sockets API. On a Unix-like system, man socket and man 7 tcp are the place to start.

Some System V Unix systems offered an alternative called TLI (Transport Layer Interface), and The Open Group standardized a variant called XTI (X/Open Transport Interface). Sockets, TLI and XTI are all general purpose: TCP/IP is one of several protocol families they can reach.

How can I detect that the other end has crashed?

With difficulty. TCP sends nothing on an idle connection, and media such as Ethernet give no reliable signal that a given host is up. If a server hears nothing from a client, the client may simply have nothing to say, a network in between may be down, a cable may be unplugged, or the client may have crashed. Many network failures are brief, for example while routes settle after a router fails, and TCP should not drop connections because of them.

Keepalives are the built-in answer. When enabled on a socket, TCP sends an empty probe on a connection that has been idle for a long time. A live peer acknowledges it, a rebooted peer answers with a reset, and a dead peer does not answer at all, so the connection eventually times out. Keepalives are off by default and the idle time is long, normally two hours. Their purpose is to free resources held by dead connections, not to detect a crash quickly.

If you need fast detection, build it into the application protocol: for example, require each client to send a no-op message every minute or two and drop the session if it stops. The X Display Manager Control Protocol (XDMCP) works this way, with the manager periodically sending a Sync to the display server. The FAQ notes that it is not a perfect example, since a client that holds the server for too long can cause a false timeout.

Can the keepalive timeouts be configured?

Yes, but how depends on the operating system. On Linux there are system-wide settings plus per-socket options, listed in the deep dive below. The FAQ also recommended the discussion of these variables in Richard Stevens' TCP/IP Illustrated, Volume 1.

Deep dive: the numbers and details

This part holds the figures, timers, formulas and worked examples. Skip it if the overview is all you need.

FieldSizeWhat it does
Source port, destination port16 bits eachIdentify the two applications (0 to 65535)
Sequence number32 bitsNumber of the first data byte in this segment
Acknowledgment number32 bitsNext byte the receiver expects
Data offset4 bitsHeader length in 32-bit words (5 to 15, so 20 to 60 bytes)
Control bitsSYN, ACK, FIN, RST, PSH, URG, ECE, CWROpen, acknowledge, close, reset and signal
Window16 bitsReceive window in bytes (scaled by the window scale option)
Checksum16 bitsCovers header, data and a pseudo-header of IP addresses
Urgent pointer16 bitsRarely used

The fixed header is 20 bytes; options such as MSS, window scale, timestamps and SACK take it up to 60. When no MSS option is received, RFC 9293 section 3.7.1 sets a default send MSS of 536 bytes for IPv4 (576 minus 40 bytes of IP and TCP headers).

Opening and closing a connection

  1. Client sends SYN with its initial sequence number x.
  2. Server replies SYN+ACK with its own number y and acknowledgment x+1.
  3. Client sends ACK y+1. Data can flow.

Closing takes a FIN from each side, each acknowledged. The side that closes first waits in TIME-WAIT for twice the maximum segment lifetime (MSL) so that stray old segments die out. RFC 9293 section 3.4.2 takes the MSL as 2 minutes, so TIME-WAIT lasts 4 minutes by the specification. This is why a busy client that opens and closes many short connections can run short of local ports.

Port ranges

Under RFC 6335 section 8.1.2, the 16-bit space splits into three ranges:

RangeNameUse
0 to 1023System PortsWell-known services such as 21 (FTP), 23 (Telnet), 53 (DNS)
1024 to 49151User PortsRegistered services
49152 to 65535Dynamic and/or Private PortsTemporary client-side ports; never assigned

A connection is identified by the four-tuple of source address, source port, destination address and destination port, so one server port can carry thousands of connections at once.

Congestion window rules from RFC 5681

The sender may have at most min(cwnd, rwnd) bytes unacknowledged, where cwnd is its congestion window and rwnd is the receiver's advertised window. RFC 5681 sets:

  • Initial window (section 3.1): 2 segments if SMSS is above 2190 bytes, 3 segments if SMSS is 1096 to 2190 bytes, 4 segments if SMSS is 1095 bytes or less.
  • Slow start: cwnd grows by up to one SMSS per ACK, which roughly doubles it every round trip, until it reaches ssthresh.
  • Congestion avoidance: cwnd grows by about one SMSS per round trip.
  • On loss: ssthresh = max(FlightSize / 2, 2 x SMSS) (equation 4).
  • Fast retransmit: triggered by 3 duplicate ACKs.

Worked example. SMSS = 1460 bytes, so the initial window is 3 segments, 4380 bytes. With slow start doubling each round trip, the window passes 3, 6, 12, 24, 48 segments. Reaching 48 segments (about 70 KB) takes 4 round trips; on a 50 ms path that is 200 ms before the connection runs at about 70 KB per 50 ms, or about 11 Mbit/s. If a loss then occurs with 48 segments in flight, ssthresh becomes 24 segments and growth continues linearly from there.

Window size and the bandwidth-delay product

To keep a link full, the window must cover the bandwidth-delay product. A 1 Gbit/s path with a 40 ms round trip needs 10^9 x 0.04 / 8 = 5 MB in flight. The plain 16-bit window field stops at 65,535 bytes, which on that path would limit throughput to about 65,535 x 8 / 0.04, roughly 13 Mbit/s. The window scale option, first in RFC 1323 and now in RFC 7323 (September 2014), allows a shift count of up to 14, giving a maximum window of 1 GiB. The same RFC defines the timestamps option, used for round-trip time measurement and for Protection Against Wrapped Sequences (PAWS) on fast links where the 32-bit sequence number can wrap.

Keepalive rules and Linux defaults

RFC 9293 section 3.8.4 says keepalives must default to off, the interval must default to no less than two hours, and the failure of any single probe must not be taken as a dead connection.

On Linux, the tcp(7) manual page gives the system defaults:

SettingDefaultPer-socket option
tcp_keepalive_time (idle before first probe)7200 sTCP_KEEPIDLE
tcp_keepalive_intvl (between probes)75 sTCP_KEEPINTVL
tcp_keepalive_probes (before giving up)9TCP_KEEPCNT

The socket must also have SO_KEEPALIVE set. With the defaults, a dead peer is detected after 7200 + 9 x 75 = 7875 seconds, about 2 hours 11 minutes. Setting TCP_KEEPIDLE to 60, TCP_KEEPINTVL to 10 and TCP_KEEPCNT to 3 on one socket cuts that to 60 + 30 = 90 seconds without changing the system default.

Nagle and TCP_NODELAY

The Nagle algorithm (RFC 896, and RFC 9293 section 3.7.4) holds back a small segment while earlier data is unacknowledged. Combined with delayed acknowledgments at the receiver, this can add noticeable latency to request-response protocols that send small writes. Setting TCP_NODELAY on the socket disables Nagle so that small segments go out at once, as the Linux tcp(7) page describes. It suits interactive and control traffic; for bulk transfers, leave Nagle on and write in large blocks.

Quick interview checks

  • TCP vs UDP: reliable ordered byte stream with connection setup, versus independent datagrams with no delivery guarantee.
  • Why three messages in the handshake: each side must send its own initial sequence number and see it acknowledged.
  • Why TIME-WAIT exists: to absorb delayed segments from the old connection and to resend the final ACK if it is lost.
  • Flow control vs congestion control: rwnd protects the receiver; cwnd protects the network.
  • Why keepalives are not a crash detector: off by default, two-hour idle time, and single missed probes must be tolerated.

Further reading

The Editor's Desk
About the Author
The Editor's Desk
Share Facebook X LinkedIn WhatsApp Email

Post a Comment

0 Comments

Your comments will be moderated before it appears here.

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!