SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 19

Cybersecurity Fundamentals · Lesson 19 of 90 · 19 min

TCP, UDP and the handshake

TCPthree-way handshakeflags (SYN, ACK, FIN, RST)sequence numbersconnection stateswell-known and ephemeral portsUDPconnectionless protocolsSYN flood (concept)SYN cookiesport scanning as a concept defenders detect

These are the notes for Cybersecurity Fundamentals (defensive), episode 19. Last episode, IP got a packet all the way to Ravi's laptop. Today we invent, one problem at a time, everything that happens next: ports and sockets, well-known and ephemeral ports, TCP with its sequence numbers, acknowledgements and retransmission, the three-way handshake and the flags SYN, ACK, FIN and RST, connection states, UDP and connectionless protocols, the SYN flood attack and the SYN cookie defence, and finally how defenders spot a port scan. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Ravi, his office and every log line are made up. The sockets in the demos only ever use 127.0.0.1, the loopback address (this same machine). All other addresses are private (RFC 1918) or reserved for documentation (RFC 5737), so nothing here touches or scans a real network. Every code sample runs with Python 3.13 using only the standard library; outputs are real, copied from actual runs. In tracebacks, long file paths are shortened to just the file name.

The problems you'll solve

Problem Idea it teaches
The packet reached the laptop, but which program is it for? Port, socket, well-known port, ephemeral port, port ranges
The network loses and shuffles packets Best effort, sequence number, acknowledgement (ACK), retransmission, TCP
Both sides must agree before talking Three-way handshake, SYN, SYN-ACK, ACK, initial sequence number (ISN)
How does a connection end, and what state is it in? FIN, RST, connection states, TIME-WAIT, stateful firewall
A late cricket score is useless UDP, datagram, connectionless protocol
Fake bookings fill every table SYN flood, backlog, half-open connection, spoofing, denial of service
Store nothing for strangers SYN cookies, HMAC
Someone tries every door Port scan (open / closed / filtered), detection, attack surface

Problem 1: which program? Ports and sockets

A courier needs two things: the building address to reach the gate, and the flat number to find the right family inside.

  • The IP address (episode 18) gets a packet to the right machine.
  • A port gets it to the right program on that machine. A port is a 16-bit number, so it goes from 0 to 65535. A browser, a chat app and an update service each use their own port.

Some flats are famous: the society office is always flat 1. Servers use fixed, well-known ports in the same way, so clients know where to knock:

Service Port What it is
HTTP 80 Web pages without encryption
HTTPS 443 Web pages with encryption (TLS, episode 22)
SSH 22 Secure Shell: an encrypted remote login
DNS 53 The Domain Name System: names to addresses (episode 20)

A visitor gets a guest room for one stay. When your browser connects to a server, the operating system gives the browser a temporary port for that one connection: an ephemeral port ("ephemeral" means short-lived). The server keeps its fixed port; the client uses a throwaway one.

Port ranges

IANA (the Internet Assigned Numbers Authority, the body that hands out Internet numbers) splits ports into three ranges, documented in RFC 6335:

Range Name Used for
0 – 1023 System ports (also called well-known ports) Standard services: 22, 53, 80, 443
1024 – 49151 User ports (also called registered ports) Other registered services, e.g. 3306 (MySQL)
49152 – 65535 Dynamic and/or private ports Never assigned: free for temporary (ephemeral) use

Operating systems choose their own ephemeral range. The Linux machine these notes were run on reads 32768 60999 from /proc/sys/net/ipv4/ip_local_port_range, so a client port like 39114 is perfectly normal there.

Sockets

A program talks to the network through a socket: an endpoint made of an IP address, a port and a protocol (TCP or UDP). Think of it as the program's own letterbox. A server binds a socket to a port (claims that port) and then listens for connections.

Demo 1: two programs, one port

import socket

for name in ["http", "https", "ssh", "domain"]:
    print(f"{name:7} -> well-known port",
          socket.getservbyname(name, "tcp"))

shop = socket.socket()            # app 1: a web shop
shop.bind(("127.0.0.1", 8080))    # takes door 8080
shop.listen()
print("shop is listening on port 8080")

chat = socket.socket()            # app 2: a chat app
chat.bind(("127.0.0.1", 8080))    # same door?

Output:

http    -> well-known port 80
https   -> well-known port 443
ssh     -> well-known port 22
domain  -> well-known port 53
shop is listening on port 8080
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    chat.bind(("127.0.0.1", 8080))    # same door?
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 98] Address already in use

getservbyname looks the names up in the system's services list (domain is the official service name for DNS). The second bind fails: one port, one listening program, like one flat, one family.

Security view. Every listening port is an open door into the machine, part of its attack surface (the sum of all the places an attacker could try to get in, episode 1). A port you didn't expect to be open is the first thing to investigate.

Problem 2: lost and shuffled packets

A long message is split into many packets, like a letter sent as six separate envelopes. Each envelope can take a different route, so they arrive in any order, and one can simply vanish. IP is best effort: it tries to deliver, but promises nothing. No order, no delivery guarantee, and no complaint when something is lost.

Demo 2: the obvious way fails

import random
random.seed(7)                   # same "bad network" each run
message = ["Pay", "Ravi", "Rs", "500", "for", "rent"]

packets = message[:]             # sent one word per packet
random.shuffle(packets)          # the network reorders...
packets.remove("500")            # ...and loses one
print("received:", " ".join(packets))

Output:

received: for Pay rent Ravi Rs

random.seed(7) makes the "bad luck" the same on every run. The words are shuffled, the amount is gone, and the receiver can't even tell that something is missing.

The fix: number, acknowledge, re-send

  1. Write a number on every piece: a sequence number, like "page 3 of 6". The receiver can put pieces back in order.
  2. The receiver tells the sender what arrived: an acknowledgement, ACK for short.
  3. If the sender gets no ACK in time, it sends that piece again: retransmission.

Demo 3: sequence numbers and re-sending

import random
random.seed(7)
message = ["Pay", "Ravi", "Rs", "500", "for", "rent"]

packets = list(enumerate(message))   # (seq, word)
random.shuffle(packets)
packets = [p for p in packets if p[1] != "500"]  # lost

got = dict(packets)                  # receiver: by seq
missing = [s for s in range(6) if s not in got]
print("ACK says missing seq:", missing)
for s in missing:                    # sender re-sends
    got[s] = message[s]
print("rebuilt:", " ".join(got[s] for s in sorted(got)))

Output:

ACK says missing seq: [3]
rebuilt: Pay Ravi Rs 500 for rent

You just invented the heart of TCP, the Transmission Control Protocol. TCP turns best-effort packets into a reliable, ordered stream of bytes. Its current standard is RFC 9293 (August 2022, Internet Standard STD 7), which replaced the original RFC 793.

How real TCP does it:

  • It numbers every byte (octet), not every word. The sequence number space is 32 bits, and the arithmetic wraps around.
  • ACKs are cumulative: "ACK 500" means "I have everything before byte 500; send 500 next".
  • One TCP piece (header + data) is called a segment. The small label in front of it is the TCP header: source port, destination port, sequence number, acknowledgement number, flags and more.

Problem 3: the three-way handshake

Before numbering anything, both sides must agree on two things: that the other side is really there, and where each one starts counting. Think of a call on a bad line:

  1. "Hello, can you hear me? I'll start counting from 100."
  2. "Yes! Can you hear me? I got your 100; I'll start from 300."
  3. "Yes, I got your 300. Let's talk."

That's the three-way handshake. Using the example numbers from RFC 9293 itself:

Client                                   Server (port 443)
  | ---- SYN      seq=100 ----------------> |   "let's talk, I start at 100"
  | <--- SYN-ACK  seq=300  ack=101 -------- |   "got 100, I start at 300"
  | ---- ACK      ack=301 ----------------> |   "got 300"   → ESTABLISHED
  | ==== data, every byte numbered =======> |
  • SYN ("synchronise") starts a connection and announces the sender's first sequence number.
  • SYN-ACK has both flags on: it acknowledges the client's SYN (ack=101: the next number I expect) and sends the server's own first number.
  • ACK confirms the server's number. Both sides are now established.

A SYN uses up one sequence number, which is why the reply says 101, not 100.

TCP flags

A flag is a single on/off bit in the TCP header.

Flag Meaning
SYN Start a connection; synchronise my sequence number
ACK The acknowledgement number in this segment is valid
FIN "Finish": I'm done sending; close politely
RST "Reset": abort right now; this connection doesn't exist
PSH, URG Push data to the application now; urgent data (rarely used)
ECE, CWR Congestion signalling (Explicit Congestion Notification)

The initial sequence number must be unpredictable

The first sequence number is the initial sequence number (ISN). RFC 9293 says it must come from a clock plus a pseudorandom function of the connection's addresses and ports and a secret key, and that outsiders must not be able to compute it. Why? If an attacker could guess the numbers, they could forge segments that look like part of your connection (inject data or reset it).

Closing: FIN and RST

To end politely, each side sends a FIN and the other acknowledges it. Each direction closes separately, so the tidy goodbye usually takes four messages (FIN, ACK, FIN, ACK). An RST ends a connection immediately. A closed port answers a SYN with an RST.

Demo 4: a real handshake on loopback

import socket

server = socket.socket()               # TCP by default
server.bind(("127.0.0.1", 9000))
server.listen()                        # state: LISTEN

client = socket.create_connection(("127.0.0.1", 9000))
conn, addr = server.accept()           # handshake done
print("client side:", client.getsockname())
print("server side:", conn.getsockname())
client.sendall(b"hello")
print("server got:", conn.recv(100))

client.close(); conn.close(); server.close()
socket.create_connection(("127.0.0.1", 9001))  # nobody

Output (the client port is chosen by the system, so yours will differ):

client side: ('127.0.0.1', 39114)
server side: ('127.0.0.1', 9000)
server got: b'hello'
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    socket.create_connection(("127.0.0.1", 9001))  # nobody
    ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "socket.py", line 868, in create_connection
    raise exceptions[0]
  File "socket.py", line 853, in create_connection
    sock.connect(sa)
    ~~~~~~~~~~~~^^^^
ConnectionRefusedError: [Errno 111] Connection refused
  • create_connection sends the SYN; the kernel answers with SYN-ACK and completes the handshake; accept hands the established connection to the server program.
  • The server side uses its fixed port 9000; the client side got an ephemeral port.
  • Port 9001 has no listener, so the SYN came back with an RST, which Python reports as ConnectionRefusedError: [Errno 111] Connection refused.

Problem 4: a connection has a life (states)

A TCP connection is always in exactly one state: a name for where it is in its life. RFC 9293 lists them:

State Meaning
CLOSED No connection at all
LISTEN A server waiting for connections
SYN-SENT Client sent a SYN, waiting for SYN-ACK
SYN-RECEIVED Server got a SYN, sent SYN-ACK, waiting for the final ACK (a half-open connection)
ESTABLISHED Handshake done; data flows
FIN-WAIT-1 / FIN-WAIT-2 I closed first; waiting for the other side's ACK and FIN
CLOSE-WAIT The other side closed; my program still has to close
LAST-ACK I sent my FIN after theirs; waiting for the last ACK
CLOSING Both sides sent FIN at the same time
TIME-WAIT I closed first; waiting 2 × MSL before the ports can be reused

The MSL, maximum segment lifetime, is how long a segment may survive in the network. RFC 9293 takes it as 2 minutes, so TIME-WAIT lasts 4 minutes. The point: late, stray segments from the old connection die out before a new connection reuses the same addresses and ports.

Demo 5: a toy state machine

A state machine is a table: (current state, event) → next state.

# a toy TCP state machine: (state, event) -> next state
T = {("CLOSED", "send SYN"): "SYN-SENT",
     ("SYN-SENT", "got SYN-ACK, send ACK"): "ESTABLISHED",
     ("ESTABLISHED", "send FIN"): "FIN-WAIT-1",
     ("FIN-WAIT-1", "got ACK"): "FIN-WAIT-2",
     ("FIN-WAIT-2", "got FIN, send ACK"): "TIME-WAIT",
     ("TIME-WAIT", "wait 2 x MSL"): "CLOSED"}

def run(events):
    state = "CLOSED"
    for e in events:
        state = T[(state, e)]
        print(f"  {e:22} -> {state}")

run(["send SYN", "got SYN-ACK, send ACK", "send FIN",
     "got ACK", "got FIN, send ACK", "wait 2 x MSL"])
print("now a packet that skips the handshake:")
run(["send data"])

Output:

  send SYN               -> SYN-SENT
  got SYN-ACK, send ACK  -> ESTABLISHED
  send FIN               -> FIN-WAIT-1
  got ACK                -> FIN-WAIT-2
  got FIN, send ACK      -> TIME-WAIT
  wait 2 x MSL           -> CLOSED
now a packet that skips the handshake:
Traceback (most recent call last):
  File "main.py", line 18, in <module>
    run(["send data"])
    ~~~^^^^^^^^^^^^^^^
  File "main.py", line 12, in run
    state = T[(state, e)]
            ~^^^^^^^^^^^^
KeyError: ('CLOSED', 'send data')

There's no rule for data without a handshake, so it is rejected. That is exactly the idea behind a stateful firewall: it tracks the state of every connection and drops packets that don't belong to a connection it knows (episode 24).

Problem 5: UDP, when late is useless

TCP is registered post: signed for, numbered, re-sent if lost. Perfect for web pages, payments and files.

But a live cricket score is different. If one update is lost, re-sending an old score is useless; the next ball has already been bowled. Video calls, online games and live streams feel the same. For them there is UDP, the User Datagram Protocol (RFC 768, J. Postel, 28 August 1980). Its standard says it offers "a minimum of protocol mechanism" and that "delivery and duplicate protection are not guaranteed", on purpose.

  • UDP is connectionless: no handshake, no states, no ACKs. Like dropping a postcard in a post box.
  • Each UDP message is a datagram, and it travels on its own.
  • The UDP header is just 8 bytes: source port, destination port, length and checksum (16 bits each).
  • Used by DNS lookups, voice and video calls, games, and QUIC (the transport under HTTP/3, episode 21).
TCP UDP
Connection Three-way handshake first None
Delivery Reliable: ACKs and retransmission Not guaranteed
Order Ordered by sequence numbers Any order
Header 20+ bytes 8 bytes
Good for Web, email, files, payments Live media, games, DNS

Demo 6: UDP on loopback

import socket

rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
rx.bind(("127.0.0.1", 9100))

tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tx.sendto(b"score 245/3", ("127.0.0.1", 9100))  # no handshake
data, sender = rx.recvfrom(100)
print("got", data, "from", sender[0])

n = tx.sendto(b"score 246/3", ("127.0.0.1", 9199))  # nobody
print("sent", n, "bytes to an empty port: no error!")

Output:

got b'score 245/3' from 127.0.0.1
sent 11 bytes to an empty port: no error!

SOCK_DGRAM means datagram, i.e. UDP. TCP refused loudly; UDP let the second score fall on the floor without a word. If an application needs to know, it must add its own acknowledgements and timeouts.

Security view.

  • No handshake means the source address is easy to fake (spoof). That powers reflection and amplification DDoS attacks (episode 23).
  • Silence is ambiguous: no answer could mean the port is closed, filtered by a firewall, or the program simply ignored the message.

Problem 6: the SYN flood

Remember SYN-RECEIVED? After a SYN, the server reserves memory for the half-finished connection (a half-open connection) and waits for the final ACK. The list of half-open connections a server will hold is its backlog, and it has a limit.

Picture a restaurant with five tables that holds a table for every phone booking for 15 minutes. A prankster books all five under fake names and nobody turns up. A real family walks in: "Sorry, fully booked." The restaurant is empty, yet nobody can eat.

Demo 7: a toy backlog fills up

BACKLOG = 5                # half-open slots the server keeps
half_open = []

def syn(src):              # a SYN arrives: reserve a slot
    if len(half_open) >= BACKLOG:
        return f"{src}: DROPPED, backlog full"
    half_open.append(src)  # wait for the final ACK...
    return f"{src}: SYN-ACK sent, waiting"

for i in range(1, 6):      # SYNs from fake addresses
    syn(f"198.51.100.{i}") # (they never send the ACK)
print("half-open:", len(half_open), "of", BACKLOG)
print(syn("192.168.1.9 (real customer)"))

Output:

half-open: 5 of 5
192.168.1.9 (real customer): DROPPED, backlog full

This is a real attack, the SYN flood, described in RFC 4987 (W. Eddy, August 2007): it "exhausts the backlog of half-open connections". Attackers spoof (fake) the source addresses, so the server's SYN-ACKs go nowhere and the slots stay full. The attack was publicised in 1996, attacks were seen in the wild by September 1996, and CERT Advisory CA-96.21 (September 1996) warned everyone. It is a denial of service (DoS) attack: the goal is not to steal anything, but to stop real users being served.

Why the obvious fixes don't work

Obvious fix Why it fails
A bigger backlog The attacker just sends more SYNs
A shorter wait Real users on slow mobile networks fail too
Block the attacker's IP The source addresses are fake and change with every packet

The real problem: the server stores state for strangers before they've proven anything.

Problem 7: SYN cookies

New restaurant rule: no booking register. Each caller gets a token showing their name and the time, stamped with the manager's secret stamp. The restaurant keeps nothing. When someone walks in, they show the token: a real stamp and a recent time means "seat them"; a forged or old token is refused. Pranksters can call all day and nothing fills up.

In TCP the token is the server's own sequence number in the SYN-ACK. The client must echo it back (plus one) in its final ACK, so the server can rebuild what it needs from the ACK itself.

We use an HMAC (a keyed fingerprint, episode 12): a hash that only someone with the secret key can compute.

import hmac, hashlib
SECRET = b"server-only-secret"  # never leaves the server

def cookie(who, minute):        # becomes our sequence number
    msg = f"{who}|{minute}".encode()
    d = hmac.new(SECRET, msg, hashlib.sha256).digest()
    return int.from_bytes(d[:4], "big")      # 32 bits

def ack_ok(who, now, ack):      # final ACK must be cookie + 1
    ok = [cookie(who, now), cookie(who, now - 1)]
    return ack - 1 in ok

who = "192.168.1.9:51000"
c = cookie(who, 1000)           # SYN-ACK sent, NOTHING stored
print("SYN-ACK seq (cookie):", c)
print("real ACK ok?   ", ack_ok(who, 1001, c + 1))
print("guessed ACK ok?", ack_ok(who, 1001, 12345))
print("too late ok?   ", ack_ok(who, 1003, c + 1))

Output:

SYN-ACK seq (cookie): 3250282826
real ACK ok?    True
guessed ACK ok? False
too late ok?    False
  • A real client echoes cookie + 1: accepted.
  • A guessed number fails, because nobody without SECRET can compute the cookie.
  • An ACK arriving minutes too late fails: the cookie expired (we accept only this minute and the previous one).

Real SYN cookies (RFC 4987, Appendix A) pack three things into the 32-bit sequence number: a slowly increasing time counter, a code for the maximum segment size the client asked for, and a secret function of the addresses and ports. On Linux the setting net.ipv4.tcp_syncookies defaults to 1 (Ubuntu docs: on since 9.04), which means cookies are used only when the kernel suspects a SYN flood; the machine these notes ran on also reports 1.

SYN cookies are one layer. Real networks add rate limits on firewalls and DDoS protection services (episode 23): defence in depth.

Problem 8: spotting port scans

Picture a hotel corridor at 2 a.m. One person walks the whole floor and tries every door handle. On a network, that is a port scan: sending probes to many ports to see which ones answer.

Reply to a SYN What the scanner learns
SYN-ACK Open: a program is listening
RST Closed: nothing listening, but the host is there
No reply Filtered: a firewall probably dropped it

Guests use one or two doors; nobody normal tries forty. That pattern is what a defender looks for. Only scan systems you are authorised to test: your own, or with written permission.

Demo 9: detecting a scan in a made-up log

from collections import defaultdict
# made-up firewall log: (second, source IP, destination port)
log = [(1, "192.168.1.7", 443), (2, "192.168.1.7", 443),
       (3, "192.168.1.9", 22), (4, "192.168.1.9", 443)]
log += [(5 + p // 10, "203.0.113.66", p)   # many doors,
        for p in range(20, 120)]           # one visitor

ports = defaultdict(set)
for sec, src, dport in log:
    if sec <= 60:                    # a one-minute window
        ports[src].add(dport)

for src, seen in ports.items():
    flag = "ok"
    if len(seen) > 20:
        flag = "ALERT: possible port scan"
    print(f"{src:13} {len(seen):3} ports  {flag}")

Output:

192.168.1.7     1 ports  ok
192.168.1.9     2 ports  ok
203.0.113.66  100 ports  ALERT: possible port scan

Intrusion detection systems use the same idea with smarter thresholds (episode 26). And the best defence happens before any scan: close services you don't need and put a default-deny firewall in front of the rest. A scanner can't find a door that isn't there.

The next problem

TCP can now reach any program on any machine, given an IP address and a port. But people never type numbers; they type names like shop.example.com. Who turns names into numbers, and what if someone lies in the answer? That's DNS, next episode.

The whole chain

  1. Which program? → ports, sockets, well-known and ephemeral ports
  2. Lost and shuffled packets → sequence numbers, ACKs, retransmission = TCP
  3. Agree first → three-way handshake: SYN, SYN-ACK, ACK; unpredictable ISN
  4. A life cycle → connection states, TIME-WAIT, stateful firewalls
  5. Late is useless → UDP, connectionless datagrams
  6. Fake bookings → SYN flood
  7. Store nothing → SYN cookies
  8. Every door tried → port scan detection

...and you just invented TCP and UDP.

Common mistakes (and what they print)

Mistake What you get Why Fix
Two programs bind the same port OSError: [Errno 98] Address already in use One listening program per port (and protocol) Pick a free port, or stop the old process
Connecting before the server listens ConnectionRefusedError: [Errno 111] Connection refused A closed port answers with RST Start the server first; check host and port
sendto() over UDP and assuming it arrived No error at all; the data is silently lost UDP has no handshake and no ACKs Application-level ACKs and timeouts, or TCP
Data before a handshake in a state table KeyError: ('CLOSED', 'send data') No transition exists for it Drop packets that don't match a known connection
Leaving unused services listening Found by the first port scan Every open port is attack surface Close them; default-deny firewall
"Just make the backlog bigger" against SYN floods Still flooded The attacker scales up for free SYN cookies, rate limits, DDoS protection

Mini project: Ravi's port audit

Compare what is actually listening on a server with what should be listening, name each port, and classify it by IANA range. On a real server the listening list would come from a tool like ss -ltnu; here it is made up.

import socket

# what Ravi's server says is listening (made-up, like `ss -ltnu`)
listening = [("tcp", 22), ("tcp", 443), ("tcp", 3306),
             ("udp", 53), ("tcp", 8080), ("tcp", 31337)]
# what SHOULD be listening, agreed with the team
allowed = {("tcp", 22), ("tcp", 443), ("udp", 53)}

def name_of(proto, port):
    try:
        return socket.getservbyport(port, proto)
    except OSError:
        return "unknown"

def kind(port):
    if port <= 1023:
        return "system"
    return "user" if port <= 49151 else "dynamic"

for proto, port in listening:
    status = "ok" if (proto, port) in allowed else "UNEXPECTED: investigate"
    print(f"{proto}/{port:<6} {name_of(proto, port):10} {kind(port):8} {status}")

Output:

tcp/22     ssh        system   ok
tcp/443    https      system   ok
tcp/3306   mysql      user     UNEXPECTED: investigate
udp/53     domain     system   ok
tcp/8080   http-alt   user     UNEXPECTED: investigate
tcp/31337  unknown    user     UNEXPECTED: investigate

A database port (3306) open to the network, a forgotten test server on 8080, and an unknown port: three things to investigate. Ideas to extend it: read the allowlist from a file, and print a one-line summary of how many unexpected ports were found.

Practice

1. Homework: change the seed in the loss demo and rebuild. Lose a random packet instead of always "500".

Solution
import random
for seed in [1, 2, 3]:
    random.seed(seed)
    message = ["Pay", "Ravi", "Rs", "500", "for", "rent"]
    packets = list(enumerate(message))
    random.shuffle(packets)
    lost = random.choice(packets)          # lose a random packet
    packets.remove(lost)
    got = dict(packets)
    missing = [s for s in range(6) if s not in got]
    for s in missing:
        got[s] = message[s]
    print(f"seed {seed}: lost seq {missing}, rebuilt:",
          " ".join(got[s] for s in sorted(got)))

Output:

seed 1: lost seq [0], rebuilt: Pay Ravi Rs 500 for rent
seed 2: lost seq [0], rebuilt: Pay Ravi Rs 500 for rent
seed 3: lost seq [1], rebuilt: Pay Ravi Rs 500 for rent

Whatever is lost and however it is shuffled, sequence numbers plus re-sending always rebuild the message.

2. Homework: add CLOSE-WAIT and LAST-ACK to the state machine. Model the side that closes second.

Solution
T = {("ESTABLISHED", "got FIN, send ACK"): "CLOSE-WAIT",
     ("CLOSE-WAIT", "send FIN"): "LAST-ACK",
     ("LAST-ACK", "got ACK"): "CLOSED"}

def run(events, state="ESTABLISHED"):
    for e in events:
        state = T[(state, e)]
        print(f"  {e:18} -> {state}")

print("the side that closes SECOND (passive close):")
run(["got FIN, send ACK", "send FIN", "got ACK"])

Output:

the side that closes SECOND (passive close):
  got FIN, send ACK  -> CLOSE-WAIT
  send FIN           -> LAST-ACK
  got ACK            -> CLOSED

Note that this side does not go through TIME-WAIT; only the side that closes first does. A server with thousands of connections stuck in CLOSE-WAIT usually has a bug: the program never calls close().

3. Homework: make the scan detector use a 10-second sliding window.

Solution
from collections import defaultdict
log = [(1, "192.168.1.7", 443), (2, "192.168.1.7", 443),
       (3, "192.168.1.9", 22), (4, "192.168.1.9", 443)]
log += [(5 + p // 10, "203.0.113.66", p) for p in range(20, 120)]

def detect(log, window, limit):
    alerts = set()
    for t0, src0, _ in log:                    # slide a window
        seen = {d for t, s, d in log
                if s == src0 and t0 <= t < t0 + window}
        if len(seen) > limit:
            alerts.add(src0)
    return alerts

print("10 s window, >20 ports:", detect(log, 10, 20))
print("10 s window, >5 ports: ", detect(log, 10, 5))

Output:

10 s window, >20 ports: {'203.0.113.66'}
10 s window, >5 ports:  {'203.0.113.66'}

A shorter window catches fast scans; slow scans (one port a minute) need longer windows. Real detectors use both.

4. Comment question: why must the initial sequence number be unpredictable?

Answer

Segments are accepted only if their sequence and acknowledgement numbers fit the connection. If an outsider could predict the ISN, they could forge segments with a spoofed source address that the receiver accepts: injecting data into a connection or resetting it, without ever seeing the traffic. RFC 9293 therefore requires the ISN to include a pseudorandom function with a secret key that outsiders can't compute.

5. Which side of a closed connection sits in TIME-WAIT, and for how long by the standard's MSL?

Answer

The side that closes first (the active closer). It waits 2 × MSL; with RFC 9293's MSL of 2 minutes that is 4 minutes.

6. A scanner sends SYNs to ports 22, 23 and 443 of a server. It gets SYN-ACK, RST and nothing. What does it learn?

Answer

22 is open (SYN-ACK), 23 is closed (RST), and 443 is probably filtered by a firewall (no reply). A defender wants as few open ports as possible and wants such probes logged.

Quick quiz

The client sends SYN seq=500. The server answers SYN-ACK seq=900 ack=501. What ack number does the client send?

A. 500 B. 501 C. 900 D. 901

Answer

D. 901. An acknowledgement number is the next sequence number you expect from the other side. The server's SYN used 900 (a SYN consumes one number), so the client sends ack=901.

Interview questions

  1. What is the difference between TCP and UDP? TCP is connection-oriented: a three-way handshake, sequence numbers, ACKs and retransmission give a reliable, ordered byte stream. UDP is connectionless: independent datagrams with an 8-byte header and no delivery guarantee, which makes it faster and suited to live media, games and DNS.
  2. Walk me through the three-way handshake. Client sends SYN with its ISN; server replies SYN-ACK with its own ISN and ack = client ISN + 1; client replies ACK with ack = server ISN + 1. Both are then ESTABLISHED.
  3. What do SYN, ACK, FIN and RST mean? Start and synchronise; acknowledgement field valid; graceful finish; abort immediately (also the reply from a closed port).
  4. What are well-known and ephemeral ports? Well-known (system) ports are 0–1023 for standard services; ephemeral ports are temporary client-side ports chosen by the OS (IANA's dynamic range is 49152–65535; Linux uses its own range, often 32768–60999).
  5. What is TIME-WAIT and why does it exist? The active closer waits 2 × MSL so that delayed segments from the old connection expire before the same address/port pair is reused.
  6. What is a SYN flood? A DoS attack that sends many SYNs (usually from spoofed addresses) and never completes the handshake, filling the server's backlog of half-open connections so real users are refused.
  7. How do SYN cookies work? The server encodes the connection information (time counter, MSS, and a keyed hash of addresses and ports) into its ISN and stores nothing; a legitimate ACK echoes it back + 1, and the server verifies it.
  8. How can you tell open, closed and filtered ports apart? SYN-ACK = open, RST = closed, no reply (or an ICMP error) = filtered.
  9. How would you detect a port scan? Count distinct destination ports (or hosts) per source within a time window and alert above a threshold; correlate with firewall drops and IDS alerts.
  10. Why is UDP a favourite for DDoS reflection? No handshake means the source address can be spoofed, so replies (sometimes much larger than the request) are sent to the victim.

Glossary

Term Meaning in plain words Example
Port A 16-bit number (0–65535) that picks the program on a machine 443 for HTTPS
Socket A program's network endpoint: IP address + port + protocol ('127.0.0.1', 9000) over TCP
Bind Claim a port for a socket server.bind(("127.0.0.1", 9000))
Listen Wait for incoming connections on a bound port A web server on 443
Well-known (system) port Ports 0–1023, for standard services 22 SSH, 53 DNS, 80 HTTP
Registered (user) port Ports 1024–49151, registered with IANA 3306 MySQL
Dynamic / private port Ports 49152–65535, never assigned, for temporary use A client's port
Ephemeral port A temporary client port the OS hands out for one connection 39114
IANA Internet Assigned Numbers Authority: keeps the registries of Internet numbers The port registry (RFC 6335)
Loopback The address meaning "this same machine" 127.0.0.1
Best effort Try to deliver, but promise nothing IP
Sequence number A number on each byte so the receiver can order and spot gaps seq=100
Acknowledgement (ACK) A reply saying what arrived; in TCP, the next byte expected ack=101
Retransmission Sending data again when no ACK arrives in time Re-sending "500"
TCP Transmission Control Protocol: reliable, ordered byte stream (RFC 9293) Web, email, SSH
Segment One TCP piece: header plus data A SYN segment
TCP header The label in front of a segment: ports, sequence/ack numbers, flags —
Flag One on/off bit in the TCP header SYN, ACK, FIN, RST
SYN "Synchronise": start a connection and announce my ISN First handshake message
SYN-ACK Reply with both SYN and ACK set Second handshake message
FIN "Finish": I'm done sending, close politely Closing a connection
RST "Reset": abort now; also the reply from a closed port Connection refused
Three-way handshake SYN → SYN-ACK → ACK, before any data Every TCP connection
Initial sequence number (ISN) The first sequence number of a side; must be unpredictable 100 in the RFC example
Connection state Where a TCP connection is in its life LISTEN, ESTABLISHED
Half-open connection A connection in SYN-RECEIVED, waiting for the final ACK What a SYN flood creates
TIME-WAIT The active closer waits 2 × MSL before reuse 4 minutes with a 2-minute MSL
MSL Maximum segment lifetime: how long a segment may live in the network 2 minutes (RFC 9293)
State machine A table of (state, event) → next state Demo 5
Stateful firewall A firewall that tracks connections and drops packets that don't belong Episode 24
UDP User Datagram Protocol: connectionless, no delivery guarantee (RFC 768) DNS, video calls
Datagram One independent UDP message b"score 245/3"
Connectionless protocol Sends messages without setting up a connection first UDP
Backlog The limited list of half-open connections a server keeps 5 in Demo 7
Spoofing Faking the source address (or identity) of a message Fake SYN sources
Denial of service (DoS) An attack that stops real users being served SYN flood
DDoS Distributed DoS: from many machines at once Episode 23
SYN flood Filling the backlog with SYNs that never finish the handshake CERT CA-96.21 (1996)
SYN cookie Encoding connection info in the server's ISN so nothing is stored Demo 8
HMAC A keyed hash: only someone with the secret can compute it (episode 12) hmac.new(SECRET, msg, sha256)
Port scan Probing many ports to see which are open, closed or filtered 100 ports in seconds
Open / closed / filtered SYN-ACK / RST / no reply to a probe —
Attack surface All the places an attacker could try to get in Every listening port
Intrusion detection system (IDS) A tool that watches traffic or logs for signs of attack Episode 26

Summary

  • An IP address finds the machine; a port finds the program. Ports 0–1023 are well-known, 1024–49151 registered, 49152–65535 dynamic; clients use ephemeral ports. A socket is IP + port + protocol.
  • IP is best effort. TCP adds sequence numbers, ACKs and retransmission for a reliable, ordered byte stream (RFC 9293).
  • Every TCP connection starts with the three-way handshake: SYN → SYN-ACK → ACK. Flags SYN, ACK, FIN, RST drive its life; the ISN must be unpredictable.
  • Connections move through states (LISTEN, SYN-SENT, SYN-RECEIVED, ESTABLISHED, FIN-WAIT, CLOSE-WAIT, LAST-ACK, TIME-WAIT); stateful firewalls track them.
  • UDP is connectionless: tiny header, no handshake, no promises. Fast, but easy to spoof and silent when data is lost.
  • A SYN flood fills the backlog of half-open connections; SYN cookies store nothing and hide the state in the sequence number, verified with a secret.
  • A port scan shows up as one source touching many ports; detect it by counting, and shrink your attack surface by closing what you don't need.

Next episode: DNS and its security: how names become addresses, cache poisoning, DNSSEC, DNS over HTTPS and TLS, DNS tunnelling, domain hijacking and subdomain takeover.

Sources: RFC 9293, Transmission Control Protocol (W. Eddy, Ed., Aug 2022, STD 7); RFC 768, User Datagram Protocol (J. Postel, 28 Aug 1980); IANA Service Name and Transport Protocol Port Number Registry (RFC 6335; page updated 27 Oct 2026); RFC 4987, TCP SYN Flooding Attacks and Common Mitigations (W. Eddy, Aug 2007), incl. CERT Advisory CA-96.21; Ubuntu Security documentation, "SYN cookies". Linux values read from /proc on the machine the demos ran on. Code outputs from Python 3.13. Fetched 30 Oct 2026.