Networks I: Moving Bits
How does a message cross a network that nobody owns, and what limits it at each layer?
The part opens with one datagram, 'Call me Ishmael.', sent from a Pebble in San Francisco to one in Frankfurt: 16 bytes become a 64-byte frame, and the ping takes the 108 ms that light needs in 11,020 km of fibre. The telephone network reserved a circuit for every call; Baran and Davies cut messages into packets that share links, and the Internet stacks that idea in five layers with IP at the waist. The part then climbs the layers and derives what limits each: Shannon's capacity under QAM, bit stuffing and CRC-32 for frames, ALOHA's throughput G e^(-2G) with its peak of 1/2e, Ethernet's backoff, and Perlman's spanning tree against a broadcast storm. At the network layer it builds longest-prefix match with tries, distance vector with its count to infinity, link state with its transient loops, and BGP, where an equal-prefix hijack takes 50 of 125 systems and a sub-prefix hijack all of them. It assembles these into its own internet of eight cities with ping and traceroute, adds fading, OFDM and MIMO for wireless, and ends at the frontier: a verifier that finds a forwarding loop from the tables alone, and BAD GADGET, a set of BGP policies that never converges.
What you need. Binary and hexadecimal, logarithms, the exponential and Poisson distributions at the level of a first probability course.
- Mathematics, ideas and history
- layering and the end-to-end argument, Shannon–Hartley, ALOHA's 1/2e, Ethernet, IP and longest-prefix match, distance vector, link state, BGP
- What we build or compute
- a simulated internet of Pebbles
What you will be able to do
Degree
- Trace a datagram through the five layers, naming each header and which addresses change at every hop.
- Derive pure ALOHA's throughput G e^(-2G) and slotted ALOHA's G e^(-G), with their maxima.
- Run distance vector by hand on a small graph, and show the count to infinity after a cut.
Graduate
- Compute a channel's Shannon capacity and the gap between a QAM constellation and the limit.
- Build longest-prefix match with a binary and a multibit trie and count the memory reads.
- Explain why link-state routers that update at different times can loop, and find the loop.
Research
- State the stable paths problem, show that BAD GADGET has no stable solution, and say what Gao-Rexford policies guarantee.
- Find an order of router updates after a link failure under which no packet loops, and state what is known about the fewest rounds.
Industry
- Plan addresses with CIDR, and diagnose a path with ping, traceroute and a packet capture.
- Explain how a prefix hijack spreads, and what route-origin validation stops and does not stop.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 27 min · Graduate 44 min · Research 47 min · Industry 32 min.
- 0One datagramDegree2 min
- 1Circuits and packetsDegree2 min
- 2Layers and the end-to-end argumentDegree3 min
- 3Bits on a wireGraduate3 min
- 4FramesDegree3 min
- 5Sharing a channelDegree3 min
- 6Bridges and switchesDegree2 min
- 7IPDegree4 min
- 8ForwardingGraduate3 min
- 9Distance vectorDegree3 min
- 10Link stateDegree2 min
- 11BGPIndustry3 min
- 12Software-defined networksIndustry2 min
- 13Our internetGraduate2 min
- 14WirelessGraduate3 min
- 15Frontier: programmable, verified, convergentResearch3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
One datagramDegree2 min
Pebble 1, a computer in San Francisco, sends sixteen bytes to Pebble 2 in Frankfurt: call me Ishmael. By the time they leave the machine they are sixty-four bytes. The message is wrapped in a UDP header, which names the program it is for; that in an IP header, which names the machine; that in an Ethernet frame, which names the next box on the cable, and ends with a checksum. Here are the actual bytes, as our network builds them. Every layer adds its own envelope, and every one of them is there for a reason this part will find.
The bytes cross an internet that we simulate in this part: eight cities, ten cables, routers that forward by the rules real routers use. The route: San Francisco to New York, across the Atlantic to Paris, on to Frankfurt. Traceroute reveals it, by a trick we will meet in chapter seven, router by router: forty-six milliseconds to New York and back, a hundred and three to Paris, a hundred and eight to Frankfurt. And here is the surprise. Eleven thousand kilometres of glass, there and back, at two thirds of the speed of light, take a hundred and eight milliseconds. The routers and queues add almost nothing. The network is as fast as physics allows; what is hard is everything else.
1Circuits and packetsDegree2 min
The telephone network was built on circuits. A call reserved a path of wires and switches from end to end for as long as it lasted, which guaranteed it a fixed share of every link, whether anyone spoke or not. Computers do not talk like people. They are silent, then send a burst, then are silent again, and a reserved line sits idle most of the time. The alternative is to cut data into packets, each carrying its destination, and let every packet share every link. The six bursty users here fit on two shared lines, with a short queue when bursts coincide. The price is that nothing is guaranteed: packets can wait, arrive out of order, or be dropped when a queue overflows.
How much does sharing save? Suppose each user is active a tenth of the time, independently, and a link can carry ten active users at once. With circuits, it serves ten users. With packets, thirty-five users can share it: the number active at once follows a binomial distribution, and more than ten are active only four times in ten thousand. The saving grows with scale. A thousand users need a thousand circuits, but a packet link sized for a hundred and thirty-seven of them overflows less than once in ten thousand. This is the law of large numbers from Part 20, and it is the economic reason the Internet is built from packets.
The idea had two inventors. Paul Baran at RAND, in 1964, designed a network for the Cold War, a mesh of small message blocks that would keep working after losing most of its nodes. Donald Davies in Britain, independently, called them packets. In 1969 the ARPANET sent its first message, from UCLA to the Stanford Research Institute. It was meant to be LOGIN; the system crashed after two letters. In 1974 Vint Cerf and Bob Kahn designed a protocol to connect different networks into one, an inter-network. On the first of January 1983, ARPANET switched to it, TCP and IP. Today some seventy-five thousand independent networks run it as one Internet.
2Layers and the end-to-end argumentDegree3 min
Networks are built in layers, each a service for the one above. At the top, the application, here our sixteen bytes. Below it, transport, which delivers to the right program; network, which moves packets between machines anywhere; link, which moves frames across one cable; and the physical layer, which turns bits into signals. Sending, each layer wraps what it is given in its own header: data, then a UDP header, then IP, then an Ethernet frame. Each layer's header is read only by the same layer at the other end, as if the two talked directly. A router in the middle implements only the bottom three. It strips the frame, reads the IP header to choose the next link, and wraps the packet in a new frame for that link.
Draw the protocols the Internet actually uses, layer by layer, and the picture is an hourglass. Many applications on top; a few transports; many kinds of link at the bottom. And in the middle, at the waist, exactly one protocol: IP. Because everything speaks IP, any application runs over any link. Wi-Fi and 5G arrived without changing the web, and the web arrived without changing Ethernet. The cost is that the waist itself is almost impossible to change: IPv6 was specified in 1998, and the Internet is still moving to it. And envelopes cost bytes: sixteen bytes of data take eighty-four on the wire, a fifth efficient; full-sized packets are ninety-six percent.
Which layer should do what? In 1984 Jerome Saltzer, David Reed and David Clark gave the answer that shaped the Internet. Suppose you copy a file across the network, and every link checks every frame with a CRC. A router can still corrupt a packet while it sits in the router's own memory, where no link check can see it. Say this happens once in a billion packets. A gigabyte crosses fifteen hops in seven hundred thousand packets, and about one copy in a hundred arrives damaged, every link check having passed. Only the two ends, comparing a checksum of the whole file, can know. So the network can be simple and best-effort, and the hard guarantees live at the edges. David Clark later wrote down the priorities: the first goal was to keep working when parts of the network failed. Accounting came last.
3Bits on a wireGraduate3 min
The physical layer turns bits into a signal: a voltage on copper, light in glass, a radio wave. Two results bound what it can do. Harry Nyquist showed in 1928 that a channel of bandwidth B can carry at most two B independent pulses each second. And Claude Shannon showed in 1948, the theorem we met in Part 28, that with noise the capacity is B times the logarithm of one plus the signal-to-noise ratio. Below that rate, coding can make errors as rare as you like. Above it, nothing can. For a telephone line, thirty-six kilobits a second; for an eighty-megahertz Wi-Fi channel, eight hundred megabits; and the last dial-up modems reached thirty-three point six kilobits on such a line. The bound is not just theory: engineering gets close to it.
How do real systems approach the limit? By sending, in each symbol, one of M points in a plane: an amplitude and a phase, which together encode log two of M bits. Sixteen points, four bits a symbol. The labels are Gray-coded, so neighbouring points differ in one bit. Noise scatters each received point into a cloud, and the receiver picks the nearest point. At twenty-four decibels the clouds are tight; at fourteen they touch, and several percent of symbols are wrong. Sixty-four points carry six bits, but packed closer, they need about six decibels more signal for the same error rate.
We sent two hundred thousand random symbols for each size and signal level, and counted errors. The measured rates fall on the textbook formula's curves, and each curve sits further right, needing more signal, as the points multiply. Now compare with Shannon. To carry four bits a symbol, Shannon needs a signal-to-noise ratio of fifteen, under twelve decibels; uncoded 16-QAM needs twenty to reach one error in a million bits. The gap is about eight and a half decibels, whatever the size. Closing it is the job of Part 28's error-correcting codes. Modern links with LDPC or polar codes run within a fraction of a decibel of the limit.
Capacity is one limit; distance is the other. Light in glass travels about two hundred thousand kilometres a second, two thirds of its speed in vacuum. A round trip from New York to London takes at least fifty-five milliseconds; to Singapore and back from London, a hundred and eighteen. No engineering can lower these. Multiply the rate by the round trip and you get the bandwidth-delay product, the bytes that must be in flight to keep the pipe full. At a hundred gigabits a second across the Atlantic, six hundred and eighty-eight megabytes are in the cable at once. Part 37's TCP has to manage exactly that.
4FramesDegree3 min
A link carries a stream of bits. The first problem is to know where each frame begins and ends. One answer marks each end with a special pattern, a flag: zero, six ones, zero. But data can contain that pattern too. So the sender, whenever it has sent five ones in a row, inserts a zero, and the receiver, seeing five ones and a zero, removes it. Now six ones in a row can never appear inside a frame, and the flag is unambiguous, whatever the data. This is bit stuffing, from the HDLC family of protocols. Ethernet does it differently: a fixed preamble before each frame, and silence between them.
Below framing there is a quieter problem: the receiver must sample each bit at the right moment, and it has no wire carrying the sender's clock. It recovers the clock from the signal's edges. Sent as plain levels, a long run of zeros is a flat line, and the receiver's clock drifts until it miscounts the bits. The first Ethernet used Manchester coding: every bit is a transition, up for a one, down for a zero, so edges never stop, at the cost of signalling twice as fast. Faster Ethernets use cheaper codes: four bits in five symbols, eight in ten, and at ten gigabits and above, sixty-four bits in sixty-six, with the bits scrambled so long runs are vanishingly rare. Ninety-seven percent of the line carries data.
The second problem is noise. Each Ethernet frame ends with a frame check sequence: the remainder when the frame, read as a polynomial over two elements, is divided by a fixed polynomial of degree thirty-two. This is the cyclic redundancy check of Part 28, the same one zip files and PNG images use. We corrupted a hundred thousand frames four ways. Single flipped bits, pairs, bursts up to thirty-two bits long: every one detected, as the algebra guarantees. Even frames replaced by pure noise: none slipped through. Random garbage passes only once in four billion tries. But a CRC only detects. A damaged frame is thrown away, and whether it is ever sent again is another layer's business.
Here is an Ethernet frame, field by field, with our bytes. Six bytes of destination address and six of source. These are MAC addresses: forty-eight bits, fixed in each network interface when it is made, the first half naming the manufacturer. An address of all ones is broadcast: every machine on the cable takes the frame. Two bytes of type say what the payload is, here IPv4, so the receiving machine knows which layer to hand it to. Then the payload, and the CRC. A frame is never shorter than sixty-four bytes, and the reason is the subject of the next chapter.
5Sharing a channelDegree3 min
In 1970 Norman Abramson's ALOHAnet linked the Hawaiian islands by radio, every station sharing one frequency, with the simplest possible rule: when you have a frame, send it. If two frames overlap, both are garbled, and each sender tries again later, at random. How much gets through? Let frames start as a Poisson process, G of them per frame time, counting retries. A frame survives only if no other starts in the frame time before it or the frame time after: a window of two. The chance of that is e to the minus two G, so the throughput is G e to the minus two G. Its maximum, at G equal to a half, is one over two e: eighteen percent. If stations may start only at slot boundaries, the window halves, and the throughput doubles to one over e.
We simulated eighty thousand frames at each load. Pure ALOHA's measured throughput falls on G e to the minus two G, peaking at point one eight four; slotted ALOHA's on G e to the minus G, peaking at point three six eight. Past the peak the curves fall: more traffic means more collisions, which mean more retries, which mean more traffic. Offered too much, a random-access channel collapses, and every such protocol must keep its load below the peak.
Bob Metcalfe's Ethernet, at Xerox in 1973, improved on ALOHA in three ways. Listen before sending, and wait if the cable is busy. While sending, keep listening; if the signal is garbled, someone else started too, so stop at once. Then wait a random number of slots, doubling the range after each collision, so the more crowded the cable, the more the stations spread out. A slot is the time for a signal to cross the longest cable and come back, and a frame must last at least that long, or a sender could finish before hearing the collision. That is why frames are at least sixty-four bytes. We simulated twenty busy stations. With delay small relative to the frame, efficiency is over ninety percent. Metcalfe and Boggs's formula matches the idealized protocol exactly, and real backoff does as well or better.
Radio breaks carrier sense. Stations A and C can both reach the access point B, but not each other. Each listens, hears silence, and sends, and their frames collide at B. To each other they are back to ALOHA, and the throughput collapses as the load grows. The fix is to ask first: a short request to send, which can still collide but costs little, and B's reply, clear to send, which both A and C hear, and which reserves the air for the frame. In our simulation, at a load of two, it more than doubles the throughput. And because a radio cannot listen while it transmits, Wi-Fi cannot detect collisions as Ethernet does. It avoids them, and acknowledges every frame.
6Bridges and switchesDegree2 min
Ethernets grew by joining segments with bridges, now called switches. Connect them with spare links for redundancy, and the network has loops. A bridge that does not know where a destination is sends the frame out of every port except the one it arrived on, and a broadcast always goes everywhere. In a loop, each copy comes back around and is copied again. In our five-bridge network one broadcast becomes more than a million frames within twenty hops, and nothing stops it: unlike IP packets, Ethernet frames carry no hop count. This is a broadcast storm, and it brings a network down in seconds.
Radia Perlman, at Digital Equipment in 1985, found the cure, and wrote it up as a poem. Each bridge keeps a belief: which bridge is the root, how far away it is, and through which neighbour. Bridges tell their neighbours their beliefs, and each adopts the best offer it hears: the lowest root, then the shortest distance. The bridge with the lowest identifier becomes the root; every other bridge keeps one port towards it, and ports on any other loop-forming link are blocked. The links that stay active form a spanning tree. Now the broadcast crosses each tree link once, reaches each host once, and stops. When a link fails, the bridges recompute the tree, and a blocked port wakes up.
Bridges also learn. Each one notes the source address of every frame it sees and the port it arrived on. A frame for an address it has never seen is flooded along the tree; a frame for an address it has learned goes out of one port only. The first frame from Ana to Ben costs seven copies. Ben's reply costs three, and after that, so does every frame between them, and the rest of the network never sees them. None of this needs configuring. Plug in a switch and it works, which is a large part of why Ethernet won.
7IPDegree4 min
IP names every interface with a thirty-two-bit address, written as four numbers. The address is read as a prefix and a rest: here the first twenty-four bits name a network, ten dot four dot zero, and the last eight a machine on it. Routers forward on prefixes, not on single addresses. Since 1993 prefixes can have any length, and neighbouring prefixes that go the same way can be merged into one shorter prefix, which keeps routing tables small. Four billion addresses turned out not to be enough. Most homes now share a single public address through network address translation, the router rewriting ports on the way out and back. IPv6 has a hundred and twenty-eight bits: enough for about seven times ten to the twenty-three addresses for every square metre of the planet.
Every IP packet starts with twenty bytes. A version, a length, an identifier, the protocol inside, a checksum of the header, and the two addresses. And a time to live: every router subtracts one, and a router that brings it to zero drops the packet. That is what keeps a routing loop from circulating a packet for ever, the safeguard Ethernet frames lack. A packet too big for the next link can be cut into fragments, each with its own header, its offset in units of eight bytes, and a flag saying more follow; only the destination puts them back together. Fragments cause trouble, a lost one ruins the whole packet, so modern hosts discover the smallest link size on the path instead.
A packet carries two pairs of addresses, and they do different jobs. Follow our datagram hop by hop. The IP addresses, Pebble 1 to Pebble 2, never change; only the time to live counts down. But the Ethernet addresses change at every hop: each frame is addressed from this cable's sender to this cable's receiver, the next router. How does Pebble 1 learn its router's hardware address? It broadcasts a question on its local network: who has ten dot one dot zero dot one? The router answers with its MAC address, and Pebble 1 remembers it. That is ARP, the address resolution protocol. Nothing checks the answer, so on a local network anyone can claim to be the gateway, which is why switches in offices now watch for false replies.
The time to live also gives us traceroute, the tool behind the opening's list of routers. Send a packet with a time to live of one. The first router decrements it to zero, drops it, and, as the rules require, sends back an error message, time exceeded, from its own address. Send another with two, and the second router answers; and so on, until the destination itself replies. In our simulation: San Francisco, New York, Paris, Frankfurt, and Pebble 2. Van Jacobson wrote it in 1987, a diagnostic built entirely out of an error message. On the real Internet some routers decline to answer, and traceroute prints stars.
8ForwardingGraduate3 min
A router's forwarding table maps prefixes to next hops. A packet arrives for ten dot four dot zero dot two. Four entries contain it, from the default route, which contains everything, to a slash twenty-four. The rule is that the longest matching prefix wins, so it leaves on port seven. That rule is what lets a provider announce one large aggregate and still route a few exceptions differently. The difficulty is size. A router in the core of the Internet holds about a million IPv4 prefixes and must search them for every packet.
We built a table of a hundred thousand prefixes with the real Internet's mix of lengths, and searched it four ways. Checking every prefix is hopeless: a hundred thousand comparisons, thirty milliseconds in Python. The binary trie of Part 17 follows the address one bit at a time down a tree of prefixes, remembering the last next hop it passed: about twenty-one memory reads. A multibit trie takes eight bits at each step, expanding short prefixes so that every slot of a node is filled: under three reads, at the cost of more memory per node. All four give the same answer for every address we tried. The design choice is how much memory to spend to save reads.
How fast must this be? A port at four hundred gigabits a second receives a minimum-size packet, sixty-four bytes plus twenty of preamble and gap, every one point seven nanoseconds. A read from DRAM takes about fifty: thirty packets arrive while one memory access completes. Software cannot keep up. So routers use a special memory, the ternary content-addressable memory, which compares a key against every entry in parallel, with don't-care bits, and reports the first match. Store the prefixes longest first, and the first match is the longest match: one lookup every clock cycle. TCAMs are power-hungry, so routers also pipeline compressed tries in fast on-chip memory. Forwarding is algorithms and hardware designed together.
A fast lookup is only half of a router. The other half is the switching fabric that joins its line cards: in each time slot, every input may send one cell to one output. If each input keeps a single queue, a cell whose output is busy blocks every cell behind it, even cells for outputs sitting idle. We simulated saturated switches. Two ports deliver seventy-five percent; as the switch grows, throughput falls towards two minus the square root of two, fifty-eight point six percent, the limit Karol, Hluchyj and Morgan derived in 1987. The cure is a separate queue at each input for each output, and a matching computed every slot between inputs and outputs, as Nick McKeown's iSLIP does. Then the fabric runs at full rate.
9Distance vectorDegree3 min
The oldest way to compute routes is to gossip. Each router knows only the cost of its own links. Periodically it sends its neighbours its current table of distances, its distance vector. Each router then recomputes: the best distance to y is the cheapest neighbour, counting the link to that neighbour plus the distance the neighbour claims. This is the Bellman equation of Part 18, solved by many machines at once. Here is router u's table, round by round. At first it knows only its neighbours. Each round, news travels one hop further, and after four rounds every table has settled on the true shortest distances, the same as Dijkstra computes on the whole map. The ARPANET routed this way from 1969, and RIP still does.
Distance vector has a famous flaw. Take three routers in a line. The link from B to C fails. B knows at once that its direct route is gone. But A has been telling B, every round, that A can reach C at distance two. B does not know that A's route runs through B itself, so B concludes it can reach C through A, at three. Then A hears B say three, and updates to four. Good news spreads in a few rounds; bad news crawls, one step a round, while packets for C bounce between A and B. It ends only at the number the protocol calls infinity: sixteen, in RIP, which is why RIP networks are limited to fifteen hops.
There are patches. Split horizon: never advertise a route to the neighbour you use for it. A would not tell B about C at all. Poisoned reverse: tell that neighbour the route is infinitely long. On the line, both settle in two rounds. But in a triangle feeding a fourth router, the loop has three members, and each can still learn the dead route from another: our simulation counts to infinity just as before, with either patch. The real cure is to give routers more than a number: the whole map, which is link state, or the whole path, which is BGP.
How does distance vector do on our eight-city internet? From empty tables it converges in four rounds, the hop count of the longest shortest path. Now cut the cable from Amsterdam to Frankfurt. London's route had used it; but a path through Paris costs exactly the same, and the tables settle in three rounds. With split horizon, Amsterdam has no route at all for a round, then finds the nine-millisecond one through London and Paris. When a good alternative exists, its good news overtakes the bad. The count to infinity needs a destination that is really cut off, or an alternative far longer than what was lost. And every answer matches Dijkstra's, computed without any router ever seeing the map.
10Link stateDegree2 min
The ARPANET abandoned distance vector in 1980 for a different idea. Each router describes only its own links, in a small message called a link-state advertisement, with a sequence number so that newer news replaces older. It floods the advertisement: every router that receives a new one passes it on over every other link, once. London's reaches all eight routers of our internet in three hops. Soon every router holds the same map of the whole network, and runs Dijkstra's algorithm from Part 18 to find its shortest paths. This is OSPF, and IS-IS, inside nearly every large network today. And a failure is simply announced. Nobody has to infer it from silence, so there is no counting to infinity.
Link state is not instantaneous either. In our internet, the cable from Amsterdam to Frankfurt fails. London has been reaching Frankfurt through Amsterdam. The news floods, and each router recomputes when it gets to it: Amsterdam first, London last, two hundred milliseconds later. In between, the tables disagree. Amsterdam now sends Frankfurt's traffic back to London, and London still sends it to Amsterdam: a loop. We sent forty packets from London to Frankfurt, one every ten milliseconds, from the moment of the cut. Five died at the dead link. Sixteen bounced between London and Amsterdam until their time to live ran out. Only when London updated did packets flow again, via Paris. Real networks shorten these windows by computing backup routes in advance.
11BGPIndustry3 min
Between networks, the Internet routes by policy, not by distance. It is made of about seventy-five thousand autonomous systems, each a network under one administration, connected as customers and providers, or as peers who exchange traffic for free. At the top, a handful of tier-one networks peer with each other and buy from nobody. They speak BGP. A route carries its whole path of systems, so a system that sees itself in a path rejects it: no counting to infinity. Then money decides. Prefer routes learned from customers, who pay you; then peers; then providers, whom you pay. And never carry traffic between two of your providers for free: export peer and provider routes only to customers. Lixin Gao and Jennifer Rexford proved in 2001 that these economic rules guarantee BGP converges. On our synthetic internet of a hundred and twenty-five systems, a stub's prefix reaches every system in six rounds, over paths of three or four.
BGP believes what it is told. In February 2008 Pakistan Telecom was ordered to block YouTube within Pakistan. It announced a slash-twenty-four inside YouTube's address block, to send local traffic nowhere, and the announcement leaked to its provider, and from there to the world. Because the longest prefix wins, most of the Internet sent YouTube's traffic to Pakistan for about two hours. We repeated it on our internet. A stub claiming the same prefix as the victim captures the forty percent of systems that are closer to it. A stub claiming a more specific prefix captures every one.
The defence is cryptography, from Part 30. Through the resource public key infrastructure, the holder of an address block signs a statement: this system may originate this prefix, and nothing longer. A system that validates drops any announcement such a statement contradicts. How many must validate? Choosing validators at random on our internet, a quarter of systems validating protects about half the rest, because one validator on a path is enough to stop the bad route spreading. And if the twenty-five transit networks validate, no stub is fooled at all. Origin validation stops mistakes like Pakistan Telecom's, but not a deliberate forgery of the path, which newer proposals aim at.
12Software-defined networksIndustry2 min
Everything so far has had each router compute its own routes and forward its own packets. Software-defined networking pulls those apart. The switches only forward, by looking packets up in tables of match and action. A controller, a program on ordinary servers with a view of the whole network, computes what every table should hold and installs it. That was OpenFlow, from Stanford in 2008. Google's private backbone between its data centres runs this way, driving its links close to full, because a program with the whole picture can place traffic far better than independent routers.
Inside a data centre the network looks different again. Instead of a few huge routers, thousands of small identical switches are wired in layers, a Clos network, so that between any two racks there are many equally short paths. A four-port fat tree already gives four between every pair of pods. Switches spread traffic over the paths by hashing each flow's addresses and ports, equal-cost multipath, so that one flow's packets follow one path and stay in order. But hashing is the balls-into-bins game of Part 20. With equal flows, the busiest path carries one and a half to two times its share. Real flows are heavy-tailed, and a few elephants make it two to five times. So fabrics split flows at natural pauses, spray packets and reorder them at the receiver, or let a controller with the whole picture place the elephants.
The next step made the switches themselves programmable. In P4, a language from 2014, the programmer declares the packet's headers, a sequence of tables, and their actions, and a compiler maps them onto the switch chip, which still runs at line rate. Here is a small one, written with our instruments: parse, an access list, a longest-prefix route, a quality-of-service counter, the time to live. Four packets through it. One forwarded on port three; a voice packet counted and forwarded; one blocked by the access list; one whose time to live ran out. A new protocol used to need new chips, years away. Now it is a recompile.
13Our internetGraduate2 min
Now the whole stack at once. Our internet has eight routers in eight cities, ten cables of realistic length, and four Pebbles attached to it. Routers flood link state, compute shortest paths by delay, and forward every packet by longest-prefix match, decrementing its time to live. Pinging every pair: Frankfurt to London, seven milliseconds; San Francisco to Tokyo, eighty-one; Frankfurt to Tokyo goes east through Singapore, a hundred and sixty. Each number is the length of the cables divided by the speed of light in glass, plus a few microseconds of transmission and queueing.
Propagation is fixed, but queueing is not. We loaded a hundred-megabit link in our internet with random full-sized packets and sent four hundred pings across it. At low load the pings barely notice. As the link gets busy, the time spent waiting grows like rho over one minus rho, the Pollaczek-Khinchine formula of Part 31, and the measured waits follow it. The tail grows faster still: at ninety-five percent load, one ping in a hundred spends four and a half milliseconds in the queue. Real routers with huge buffers can turn this into seconds, a problem called bufferbloat, and how full those buffers get is decided by the congestion control of the next part.
And then we cut a cable. Traffic from London to Frankfurt had gone through Amsterdam, in seven milliseconds. After the cut, and after the routers reconverge, it goes through Paris, in eight. In between, as in chapter ten, five packets died at the dead link and sixteen looped until their time to live ran out. Every mechanism of this part took part: flooding, Dijkstra, longest-prefix match, the time to live that ended the loop. And nobody was in charge. The network found its own way around the damage, which is exactly what Paul Baran designed it to do.
14WirelessGraduate3 min
Radio adds an enemy that wires do not have. A signal reaches the receiver along many paths, bouncing off walls and buildings, and the copies arrive at slightly different times. They add or cancel, and moving a few centimetres can change the received power a hundredfold. This is fading. On a wire, errors fall exponentially as the signal grows. Under fading they fall only in proportion: in our simulation, at ten decibels, a wire makes four errors in a million bits, and a fading channel one in forty. The cure is never to depend on one path: spread the bits over many frequencies, times or antennas, so that they do not all fade together.
Echoes also smear one symbol into the next. The modern answer is to send many slow streams instead of one fast one: split the band into dozens or thousands of narrow subcarriers. Each is so narrow that the channel looks to it like a single multiplier, which the receiver can divide out. The transmitter builds the whole symbol with one inverse FFT, the algorithm of Part 19, and the receiver takes it apart with another. One trick makes it exact: repeat the end of each symbol at its start, a cyclic prefix longer than the longest echo. Then the echo is a circular convolution, which the FFT turns into multiplication. In our simulation, without the prefix, two bits in a hundred are wrong; with a prefix as long as the echo, about one in a thousand, from carriers in a deep fade. This is OFDM, the waveform of Wi-Fi, 4G, 5G and DSL.
The last trick turns the enemy into an ally. Put several antennas at each end. With many paths between them, the channel is a random matrix, and the capacity is the expected log determinant of this expression. We averaged it over four hundred random channels. One antenna at each end, at twenty decibels: six bits per second per hertz. Two: eleven. Four: twenty-two. Eight: forty-four. Capacity grows linearly with the number of antennas, with no extra power and no extra spectrum. Gerard Foschini and Emre Telatar showed it in the late 1990s. The scattering that caused fading has become a set of parallel channels, and a 5G base station now carries sixty-four antennas.
15Frontier: programmable, verified, convergentResearch3 min
The first frontier is knowing a network is right. Testing sends packets and sees what happens; verification reasons about every possible packet, directly from the forwarding tables. Our verifier follows every prefix from every router through the tables. On a snapshot taken halfway through chapter thirteen's reconvergence, it finds the London-Amsterdam loop, for two prefixes, without sending a packet; after convergence, nothing. Header space analysis, in 2012, made this general: a header is a point in a space of bits, and every rule a function on that space. Tools like Batfish now check entire configurations before they are deployed, and large clouds verify every change. The worst case is exponential in the number of header bits; what makes it fast in practice, and how to verify networks whose rules change every second, are open.
Once switches are programmable, they can do more than forward. In-band telemetry has every switch append its queue depth and a timestamp to passing packets, so the receiver sees, hop by hop, where congestion is. NetCache put a small key-value cache inside the switch, answering the hottest keys at billions of queries a second before they reach a server. And switches can sum the gradients of distributed machine learning as they pass through. What a pipeline with a few megabytes of memory and a fixed number of stages can compute, and how to verify it, are open.
The second frontier is convergence. Here are three systems around a destination. Each would rather reach it through its clockwise neighbour than directly. Start with everyone going direct. Each then sees its preferred route available and switches to it; but now each neighbour's route is indirect, so the preferred routes no longer exist, and all switch back. Our simulation cycles for ever. Timothy Griffin, Bruce Shepherd and Gordon Wilfong called this BAD GADGET, and proved that deciding whether arbitrary policies have any stable solution is NP-complete. The Gao-Rexford rules avoid it, but real policies are messier, and the guarantee is open.
Six problems at the frontier. Verifying networks whose rules change thousands of times a second. Updating every router's table in an order that never loops or drops traffic, and as quickly as possible. Securing BGP's paths, not only their origins, in a way that helps even when only some networks adopt it. Routing between networks with convergence guaranteed under the policies networks actually use. Programmable switches that are verified as well as fast. And radio that comes closer to its limits in crowded, moving channels. The research problem at the end of this part asks for the second in its simplest form: after one link fails, in what order should routers change their tables so that no packet ever loops?
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Packets instead of circuits, and the layers that wrap them. Shannon's limit and QAM measured against it. Bit stuffing and CRCs; ALOHA, Ethernet's backoff and Wi-Fi's hidden terminals; switches that learn and a spanning tree that tames loops. Addresses, prefixes and tries for forwarding in nanoseconds. Distance vector and its count to infinity, link state and its microloops, BGP's policies and its hijacks. Our own internet, wireless channels, and networks you can program and verify.
Where this comes back. Part 37 builds TCP, a reliable stream on top of packets that can be lost, and the congestion control that keeps the Internet from collapsing as ALOHA does. Part 38 makes machines agree over a network that delays and drops messages. Part 39 replicates data across these latencies. Part 42 puts HTTP and the browser on top. And Part 45 rents networks by the hour, in the cloud.
In practice. Plan addresses with CIDR, and run IPv6 alongside IPv4. Diagnose with ping and traceroute, or mtr, which combines them, and look at the packets themselves with tcpdump or Wireshark. When small transfers work and large ones hang, suspect a link with a smaller MTU whose error messages are being filtered. For Wi-Fi, choose uncrowded channels, and use several quiet access points rather than one loud one. And if you run BGP, filter what your customers may announce, sign your routes, and drop invalid ones.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add the RIP protocol to our internet as real packets, and watch the count to infinity happen to traffic. The last, marked with a star, is a research problem: after a link fails, in what order should routers install their new tables so that nothing ever loops, and how fast can that be done?
Next time, Part 37: Networks, reliable conversation. IP loses, reorders and duplicates packets, and TCP turns that into a reliable stream. In October 1986 the Internet collapsed under its own traffic, and Van Jacobson's fix, additive increase and multiplicative decrease, is why it still works. We fetch the novels over our own TCP on a lossy link. Part 37, Networks.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 37 builds TCP on these lossy packets, and congestion control that keeps the network from collapsing as ALOHA does. Part 38 makes machines agree over a network that delays and drops messages, and Part 39 replicates data across its latencies. Part 42 puts HTTP and the browser on top, and Part 45 rents networks in the cloud.
Key results
The part's results in one place, for revision.
Try it
Lab 36 · ALOHA's 1/2e and the count to infinity
Simulate pure and slotted ALOHA as Poisson processes and compare the throughput with G e^(-2G) and G e^(-G). Then cut a link under distance-vector routing and count the rounds until the dead route reaches 16, with and without split horizon, on a line and on a triangle.
python -m videos.cs.labs 36
needs numpy, scipy, matplotlib · download lab36.py ·
source on GitHubpure ALOHA at G = 0.5 measured S = 0.183 formula 0.184
slotted ALOHA at G = 1 measured S = 0.366 formula 0.368
line A-B-C, cut B-C, plain 15 rounds; shortest believed distance: 1 2 3 4 5 6 7 ...
line A-B-C, cut B-C, split 2 rounds; shortest believed distance: 1 2 16 16 ...
triangle with D on C, cut C-D, plain 15 rounds; shortest believed distance: 1 2 3 4 5 6 7 ...
triangle with D on C, cut C-D, split 15 rounds; shortest believed distance: 1 2 3 4 5 6 7 ...
Throughput follows G e^(-2G) and G e^(-G), so offering more than G = 1/2 (or 1) delivers less; and a distance vector forgets a dead route only by counting up to 16, which split horizon cures for two routers but not for three.
The code (85 lines; it asserts its own result)
"""Lab 36: measure ALOHA against G e^(-2G) and G e^(-G), and watch distance vector count to infinity."""
from videos.coursekit import labs
import math
import random
import numpy as np
from explainer.cs.net import mac
from explainer.cs.net import routing
TITLE = "ALOHA's 1/2e and the count to infinity"
GOAL = ("Simulate pure and slotted ALOHA as Poisson processes and compare the throughput with G e^(-2G) and G e^(-G). "
"Then cut a link under distance-vector routing and count the rounds until the dead route reaches 16, with and "
"without split horizon, on a line and on a triangle.")
TASKS = [
"Raise the offered load to G = 3 in both protocols. How many attempts does one delivered frame cost in each?",
"Run the line with mode='poison' and infinity=64. Which of the two changes the number of rounds, and why?",
"Make the triangle a square (A-B-C-E-A, with D on C) and cut C-D under split horizon. How long does it count now?",
]
LINE = {"A": {"B": 1}, "B": {"A": 1, "C": 1}, "C": {"B": 1}}
TRIANGLE = {"A": {"B": 1, "C": 1}, "B": {"A": 1, "C": 1}, "C": {"A": 1, "B": 1, "D": 1}, "D": {"C": 1}}
def run(seed=0):
rng = random.Random(seed)
lab = labs.Lab()
Gs = [0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0]
pure = [mac.aloha(G, 40_000, rng)["S"] for G in Gs]
slotted = [mac.slotted_aloha(G, 40_000, rng)["S"] for G in Gs]
for G, s, f in ((0.5, pure[2], 0.5 * math.exp(-1)), (1.0, slotted[4], math.exp(-1))):
name = "pure ALOHA at G = 0.5" if G == 0.5 else "slotted ALOHA at G = 1"
lab.row(name, f"measured S = {s:.3f} formula {f:.3f}")
for G, p, s in zip(Gs, pure, slotted):
assert abs(p - G * math.exp(-2 * G)) < 0.012, f"pure ALOHA is on G e^(-2G) at G = {G}"
assert abs(s - G * math.exp(-G)) < 0.012, f"slotted ALOHA is on G e^(-G) at G = {G}"
assert max(pure) < 0.2 and max(slotted) < 0.385, "no load beats 1/2e or 1/e"
assert pure[-1] < 0.02, "at G = 3 the pure channel carries almost nothing: more load, less throughput"
# distance vector: converge, cut a link, run again, and follow the dead destination's distance
runs = {}
for name, net, cut, dest in (("line A-B-C, cut B-C", LINE, ("B", "C"), "C"),
("triangle with D on C, cut C-D", TRIANGLE, ("C", "D"), "D")):
for mode in ("plain", "split"):
after = routing.dv_fail(net, *cut, mode=mode)["after"]
dist = [min(t[x][dest][0] for x in t if x != dest) for t in after["history"]] # the best rumour left
runs[name, mode] = (after["converged"], dist)
lab.row(f"{name}, {mode}", f"{after['converged']} rounds; shortest believed distance: {' '.join(map(str, dist[:7]))} ...")
assert dist[-1] == 16, "the dead destination ends at infinity (16)"
line, tri = "line A-B-C, cut B-C", "triangle with D on C, cut C-D"
assert runs[line, "plain"][0] == 15, "the film: 15 rounds to count to 16 on the line"
assert runs[line, "split"][0] <= 2, "split horizon ends a two-node loop at once"
assert runs[tri, "split"][0] == 15, "but the triangle still counts for 15 rounds"
steps = np.diff([d for d in runs[tri, "split"][1] if d < 16])
assert set(steps[1:]) == {1}, "around the triangle the rumour grows by one hop per round"
lab.note = ("Throughput follows G e^(-2G) and G e^(-G), so offering more than G = 1/2 (or 1) delivers less; and a "
"distance vector forgets a dead route only by counting up to 16, which split horizon cures for two "
"routers but not for three.")
fig, ax = labs.figure(2, size=(11, 4.2))
g = np.linspace(0.01, 3.2, 200)
ax[0].plot(g, g * np.exp(-2 * g), color=labs.RED, label="G e^(-2G): pure")
ax[0].plot(g, g * np.exp(-g), color=labs.BLUE, label="G e^(-G): slotted")
ax[0].scatter(Gs, pure, color=labs.RED, s=28, zorder=3, label="pure, simulated")
ax[0].scatter(Gs, slotted, color=labs.BLUE, s=28, zorder=3, label="slotted, simulated")
ax[0].axhline(1 / (2 * math.e), color=labs.MUTED, ls="--", lw=1)
ax[0].text(3.2, 1 / (2 * math.e) + 0.008, "1/2e", color=labs.MUTED, ha="right")
ax[0].set(title="ALOHA: throughput against offered load", xlabel="offered load G (attempts per frame time)",
ylabel="throughput S (frames per frame time)", ylim=(0, 0.45))
ax[0].legend(loc="upper right")
styles = {(line, "plain"): (labs.RED, "-", 3.2, "line, plain"),
(tri, "split"): (labs.GOLD, "--", 1.6, "triangle, split horizon (the same climb)"),
(line, "split"): (labs.GREEN, "-", 1.8, "line, split horizon")}
for key, (color, ls, lw, name) in styles.items():
d = runs[key][1]
ax[1].step(range(len(d)), d, where="post", color=color, ls=ls, lw=lw, label=name)
ax[1].axhline(16, color=labs.MUTED, ls="--", lw=1)
ax[1].text(0.2, 16.4, "infinity = 16", color=labs.MUTED)
ax[1].set(title="After the cut: the best distance still believed", xlabel="round", ylabel="distance to the dead destination",
ylim=(0, 18.5))
ax[1].legend(loc="lower right")
lab.fig = fig
return lab
Now change it
- Raise the offered load to G = 3 in both protocols. How many attempts does one delivered frame cost in each?
- Run the line with mode='poison' and infinity=64. Which of the two changes the number of rounds, and why?
- Make the triangle a square (A-B-C-E-A, with D on C) and cut C-D under split horizon. How long does it count now?
Problems, with solutions
Try each problem before opening its solution.
-
ALOHA. Derive pure ALOHA's throughput S = Ge^{−2G} and slotted ALOHA's Ge^{−G}, and their maxima.
Solution
Attempts (new and retried) form a Poisson process of rate G per frame time. A frame starting at t succeeds iff no other frame starts in (t − 1, t + 1), an interval of length 2: probability e^{−2G}. So S = G e^{−2G}; dS/dG = e^{−2G}(1 − 2G) = 0 at G = 1/2, where S = 1/(2e) ≈ 0.184. In slotted ALOHA a frame collides only with frames in its own slot, an interval of length 1: S = G e^{−G}, maximal at G = 1 with S = 1/e ≈ 0.368. Our simulation: 0.185 at G = 0.5 and 0.369 at G = 1.
-
What a CRC catches. Show that CRC-32 detects every burst of 32 or fewer bits, and that any CRC whose generator is divisible by x + 1 detects every odd number of bit errors.
Solution
An error is undetected iff its error polynomial E(x) is a multiple of g(x). A burst of length L ≤ 32 starting at bit i is E(x) = x^i B(x) with deg B = L − 1 ≤ 31 and B(0) = 1. Since g(0) = 1, g and x are coprime, so g | x^i B implies g | B, impossible because B ≠ 0 has degree less than 32. If (x + 1) | g, then every multiple of g vanishes at x = 1; but an error with an odd number of terms has E(1) = 1. (CRC-32's own generator has 15 terms and is not divisible by x + 1; instead it has Hamming distance 4 for frames of Ethernet's size, so it catches every 1-, 2- and 3-bit error there.)
-
Distance vector converges. Prove that synchronous distance vector reaches the shortest distances in at most n − 1 rounds when costs are positive and nothing changes.
Solution
By induction on k: after round k, D_x(y) is the cost of the cheapest path from x to y with at most k links (round 0: only x itself). Round k + 1 computes min over neighbours v of c(x, v) + D_v(y), and the cheapest path of at most k + 1 links is a first link to some v followed by the cheapest path from v of at most k links. With positive costs a shortest path is simple, so has at most n − 1 links; after round n − 1 every D is exact, and the next round changes nothing. Our six-node example settles in 4, its longest shortest path.
-
Split horizon's limit. Show that split horizon prevents every two-node loop but not a three-node one, with a counting example.
Solution
Two nodes can only loop if A's route to y is via B and B's via A; with split horizon A never tells B about a route through B, so B cannot adopt it, and vice versa. Take the triangle A, B, C with D hanging off C, and cut C–D. A and B both route to D via C, so neither advertises D to C, and C learns at once that D is unreachable. But B tells A "D at 2" (B's route is via C, not A), and A tells B the same, so each adopts the other at 3. Next round A's route is via B, so A may advertise it to C: C adopts 4 via A. The round after, B learns 5 from C... The value climbs by one each round around the loop of three, exactly our table (A, B, C) = (3, 3, ∞), (∞, ∞, 4), (∞, 5, ∞), …, reaching 16 after 15 rounds.
-
Build: RIP in our internet. Add RIP to the simulator: periodic distance vectors as real packets; cut a link and watch packets loop while it counts.
Solution
Give each router a UDP port 520 handler. Every period T (30 s in RIP; 1 s is enough here) send each neighbour a packet listing (prefix, metric) for every route, applying split horizon or not; on receipt, update routes with metric min(16, c + m) and remember the neighbour and a timeout (180 s in RIP). Forward data packets with the RIP table instead of
compute_tables. On the three-router line with T = 1 s, cutting B–C makes packets for C bounce between A and B until their TTL expires for about 15 periods, then they are dropped with "no route"; with split horizon they are dropped from the first period. Triggered updates (sending immediately on a change) shorten the plain count from 15 periods to about 15 round trips. -
★ Research. Loop-free reconvergence. After a single link failure, find an order of router updates under which no packet ever loops, and the fewest rounds such a schedule needs.
What is known, and a way in. In chapter 10, Amsterdam (next to the failure) updated before London (one hop further) and the two looped. Reversing the order, London first, leaves only drops: our
ls_reconvergereports zero loops at every instant. This is the oFIB rule (Francois and Bonaventure, 2007): for a link that goes down, a router may install its new table only after every router that currently reaches the failed link through it has done so, that is, in decreasing order of depth in the reverse shortest-path tree towards the failed link; for a link that comes up, the reverse. Each depth is a round, so the schedule takes as many rounds as the tree is deep; whether fewer rounds suffice, and how to schedule several simultaneous changes, is harder: for arbitrary forwarding changes, deciding whether a loop-free schedule of k rounds exists is NP-hard (Ludwig, Marcinkowski and Schmid, 2015). Open: tight bounds on rounds for the changes shortest-path routing actually produces, and schedules that are both loop-free and black-hole-free. Our verifier checks any proposed schedule state by state.
Notes and sources
Glossary
- packet switching: data cut into packets that share links, each carrying its destination.
- statistical multiplexing: sizing a shared link for the likely number of simultaneous users, not the maximum.
- encapsulation: each layer wrapping the unit of the layer above in its own header.
- end-to-end argument: functions such as reliability belong at the end points, which alone can complete them.
- channel capacity C = B log₂(1 + S/N): the highest rate at which arbitrarily reliable communication is possible.
- QAM: quadrature amplitude modulation, a symbol chosen from M points of amplitude and phase.
- bandwidth-delay product: the data in flight on a path, rate × round-trip time.
- bit stuffing: inserting a 0 after five 1s so that the flag 01111110 cannot appear in data.
- CRC: cyclic redundancy check, the remainder of the frame divided by a generator polynomial.
- MAC address: a 48-bit link-layer address; broadcast: all ones.
- ALOHA, CSMA/CD, CSMA/CA: random access; carrier sense with collision detection; with collision avoidance.
- binary exponential backoff: after the k-th collision, wait a random number of slots below 2^k.
- spanning tree protocol: bridges choosing a loop-free set of active links rooted at the lowest ID.
- CIDR: classless prefixes of any length; longest-prefix match: the most specific matching route wins.
- TTL: a hop count decremented by every router; ICMP: IP's error and diagnostic messages.
- distance vector, link state, path vector: routing by neighbours' distances, by the whole map, by whole paths.
- count to infinity: distance vector's slow convergence after a failure.
- autonomous system (AS): a network under one administration; BGP: the protocol between them.
- prefix hijack: announcing someone else's addresses; RPKI, ROA: signed statements of who may originate what.
- SDN, OpenFlow, P4: separating control from forwarding; programmable match-action pipelines.
- OFDM: many narrow subcarriers built with an FFT; cyclic prefix: a copy of a symbol's end before its start.
- MIMO: several antennas at each end, giving parallel spatial channels.
Sources
- J. F. Kurose and K. W. Ross, Computer Networking: A Top-Down Approach.
- L. L. Peterson and B. S. Davie, Computer Networks: A Systems Approach.
- A. S. Tanenbaum and D. J. Wetherall, Computer Networks; W. R. Stevens, TCP/IP Illustrated, vol. 1.
- D. Bertsekas and R. Gallager, Data Networks; G. Varghese, Network Algorithmics.
- D. Tse and P. Viswanath, Fundamentals of Wireless Communication.
- P. Baran, "On Distributed Communications Networks", IEEE Trans. Communications Systems (1964).
- V. Cerf and R. Kahn, "A Protocol for Packet Network Intercommunication", IEEE Trans. Communications (1974).
- J. H. Saltzer, D. P. Reed and D. D. Clark, "End-to-End Arguments in System Design", ACM TOCS (1984).
- D. D. Clark, "The Design Philosophy of the DARPA Internet Protocols", SIGCOMM (1988).
- H. Nyquist, "Certain Topics in Telegraph Transmission Theory" (1928); C. E. Shannon, "A Mathematical Theory of Communication" (1948).
- W. W. Peterson and D. T. Brown, "Cyclic Codes for Error Detection", Proc. IRE (1961).
- N. Abramson, "The ALOHA System", AFIPS (1970); R. M. Metcalfe and D. R. Boggs, "Ethernet: Distributed Packet Switching for Local Computer Networks", CACM (1976).
- R. Perlman, "An Algorithm for Distributed Computation of a Spanning Tree in an Extended LAN", SIGCOMM (1985).
- V. Srinivasan and G. Varghese, "Fast Address Lookups Using Controlled Prefix Expansion", ACM TOCS (1999).
- J. M. McQuillan, I. Richer and E. C. Rosen, "The New Routing Algorithm for the ARPANET", IEEE Trans. Comm. (1980).
- L. Gao and J. Rexford, "Stable Internet Routing Without Global Coordination", IEEE/ACM ToN (2001).
- T. G. Griffin, F. B. Shepherd and G. Wilfong, "The Stable Paths Problem and Interdomain Routing", IEEE/ACM ToN (2002).
- RIPE NCC, "YouTube Hijacking: A RIPE NCC RIS case study" (2008).
- N. McKeown et al., "OpenFlow: Enabling Innovation in Campus Networks", CCR (2008); P. Bosshart et al., "P4: Programming Protocol-Independent Packet Processors", CCR (2014); S. Jain et al., "B4", SIGCOMM (2013).
- P. Kazemian, G. Varghese and N. McKeown, "Header Space Analysis", NSDI (2012); A. Fogel et al., "A General Approach to Network Configuration Analysis" (Batfish), NSDI (2015).
- P. Francois and O. Bonaventure, "Avoiding Transient Loops During the Convergence of Link-State Routing Protocols", IEEE/ACM ToN (2007); A. Ludwig, J. Marcinkowski and S. Schmid, "Scheduling Loop-free Network Updates: It's Good to Relax!", PODC (2015).
- R. W. Chang, "Synthesis of Band-Limited Orthogonal Signals for Multichannel Data Transmission", BSTJ (1966); G. J. Foschini and M. J. Gans, "On Limits of Wireless Communications in a Fading Environment" (1998); E. Telatar, "Capacity of Multi-antenna Gaussian Channels" (1999).
About this partfrom its README
Part 36 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the first part of Act VII, Many Machines. The telephone network reserved a wire for every call; Baran and Davies proposed cutting messages into packets that find their own way. The Internet is that idea, organized in layers with IP as the narrow waist. This part derives what limits it at each layer (Shannon's capacity, ALOHA's 1/2e, the count to infinity, BGP's policies) and builds a small internet of its own.
The instruments are in explainer/cs/net/ (tested in tests/test_cs36_net.py):
phy.py: Shannon's capacity; square M-QAM with Gray labels through Gaussian noise, measured, against the textbook symbol error rate; the SNR each size needs for a bit error rate of 10⁻⁶ against Shannon's 2^k − 1; fibre round trips and bandwidth-delay products.link.py: HDLC bit stuffing and framing; Ethernet frames with their CRC-32 (Part 28's, checked againstzlib); corruption trials (single bits, pairs, bursts up to 32 bits, noise).mac.py: pure and slotted ALOHA as Poisson processes; CSMA/CD with binary exponential backoff and with the p = 1/n contention Metcalfe and Boggs analysed; the hidden terminal with and without RTS/CTS.bridge.py: LANs of bridges; flooding (the broadcast storm); Perlman's spanning tree by rounds of configuration messages, with root ports and designated ports; MAC learning.ip.py: prefixes; longest-prefix match by linear scan, binary trie and multibit tries with controlled prefix expansion; a synthetic table with the real mix of prefix lengths; aggregation; fragmentation; NAPT; the Internet checksum and IPv4 and UDP headers.routing.py: synchronous distance vector (plain, split horizon, poisoned reverse) with failures; reliable flooding; Dijkstra; link-state reconvergence with routers updating at different times, classifying every source-destination pair as delivered, dropped or looping.bgp.py: a tiered AS graph with customer, provider and peer links; path-vector propagation under Gao–Rexford preferences and export rules; origin and sub-prefix hijacks; route-origin validation against ROAs; the stable paths problem, with BAD GADGET and GOOD GADGET.sim.py: our internet, an event-driven simulator of hosts and routers on links with bandwidth, length and loss; serialization, propagation and queueing; link-state routing; TTL and ICMP time exceeded; ping and traceroute; failures with staggered reconvergence.wireless.py: BPSK under Gaussian noise and Rayleigh fading; OFDM with an FFT, a multipath channel and a cyclic prefix; MIMO capacity E log₂ det(I + (SNR/n) H H*).dataplane.py: a P4-shaped pipeline (parser, ternary, exact and LPM match-action tables, deparser) and a data-plane verifier that finds loops and black holes from forwarding tables alone.
Chapter notes
- Hook. "Call me Ishmael." from Pebble 1 in San Francisco to Pebble 2 in Frankfurt: 16 bytes become a 64-byte frame (Ethernet 14, IP 20, UDP 8, data 16, pad 2, FCS 4), shown byte by byte. Traceroute: San Francisco, New York (46.1 ms), Paris (103.3), Frankfurt (108.0); ping 108.04 ms, against 108.04 ms for light in 11,020 km of fibre.
- 1. Circuits and packets. Reserved circuits against shared packets for bursty users. Statistical multiplexing: 35 users, each active 10% of the time, on a link for 10: overflow probability 0.0004; 1,000 users need capacity for 137. Baran (1964), Davies, ARPANET's "LO" (1969), Cerf and Kahn (1974), the 1983 flag day.
- 2. Layers. Five layers and encapsulation, animated; a router implements three. The hourglass with IP at the waist. Overhead: 16 bytes of data take 84 on the wire (19%), 1,460 take 1,526 (96%). The end-to-end argument in numbers: a router corrupting one packet in 10⁹, a gigabyte over 15 hops: 1.0% of copies damaged with every link check passing.
- 3. Bits on a wire. Nyquist and Shannon: a telephone line 36 kb/s (modems reached 33.6), 80 MHz Wi-Fi at 30 dB 797 Mb/s. QAM clouds at 24 and 14 dB. Measured error rates on the formula; the SNR needed for 10⁻⁶ against Shannon: 4-QAM 13.5 against 4.8 dB, 16-QAM 20.4 against 11.8, 64-QAM 26.6 against 18.0, 256-QAM 32.5 against 24.1, a gap of about 8.6 dB that coding closes. Fibre round trips (New York–London 55 ms) and the bandwidth-delay product (688 MB at 100 Gb/s).
- 4. Frames. Bit stuffing. Line codes and clock recovery: Manchester (50%), 4B/5B and 8b/10b (80%), 64b/66b (97%). CRC-32: 100,000 corrupted frames of each kind, none undetected. The Ethernet frame, MAC addresses, broadcast, ethertype.
- 5. Sharing a channel. ALOHA's timeline and derivation; measured throughput on Ge^{−2G} (peak 0.184) and Ge^{−G} (0.368). CSMA/CD and binary exponential backoff; why frames are at least 64 bytes; 20 stations: efficiency measured against Metcalfe and Boggs for a = 0.01 … 0.5. The hidden terminal: throughput Ge^{−G}; RTS/CTS 0.63 at G = 2 against 0.27.
- 6. Bridges and switches. A broadcast storm: 1,115,742 frames within 20 hops in a five-bridge loop. Perlman's spanning tree (3 rounds, 3 links blocked); the broadcast then takes 8 frames. MAC learning: 7 copies, then 3.
- 7. IP. Prefixes, CIDR aggregation (four /24s into a /22), NAT, IPv6's 6.7 × 10²³ addresses per square metre. The IPv4 header, TTL, fragmentation of 4,000 bytes into a 1,500-byte MTU. ARP, and addresses hop by hop: IP addresses fixed, MAC addresses and TTL changing. Traceroute's TTL trick.
- 8. Forwarding. Longest-prefix match. 100,000 prefixes: linear 100,000 reads (34 ms in Python), binary trie 21 reads (5.1 µs), stride-4 trie 5.4, stride-8 trie 2.9; all equal. 400 Gb/s: a packet every 1.68 ns; TCAMs. Head-of-line blocking in an input-queued switch: 0.75 for 2 ports falling to 0.593 for 32 (limit 2 − √2 = 0.586); virtual output queues 1.0.
- 9. Distance vector. Bellman–Ford as gossip: u's table settling in 4 rounds. Count to infinity on a line (15 rounds to 16); split horizon and poisoned reverse fix it in 2, but a triangle still counts for 15. On our internet: 4 rounds from scratch; cutting Amsterdam–Frankfurt settles in 3 (an equal path via Paris), 5 with split horizon.
- 10. Link state. Flooding (London's LSA: 13 messages, 3 hops) and Dijkstra. A cable cut with staggered updates: of 40 packets, 5 dropped, 16 looping between London and Amsterdam, 19 delivered via Paris.
- 11. BGP. Path vector; customer > peer > provider and valley-free export (Gao and Rexford); 125 ASes converge in 6 rounds, mean path 3.3. The 2008 YouTube hijack; on our internet an equal-prefix hijack takes 50 of 125 ASes, a sub-prefix hijack all 125. RPKI: hijacked share against adoption (85% at 10%, 49% at 25%, 15% at 50%, 3% at 75%); if the 25 transit networks validate, 0%.
- 12. Software-defined networks. OpenFlow's split of control and data; Google's B4; a P4-shaped pipeline processing four packets (forward, count, drop by ACL, TTL expiry). Data-centre fabrics: a k = 4 fat tree (16 hosts, 20 switches, 4 paths between pods); ECMP's busiest path at 1.5–2.0 times the mean for equal flows, 2.1–5.0 for heavy-tailed flows.
- 13. Our internet. Eight cities, four Pebbles, a ping matrix (London–Frankfurt 7.1 ms, Frankfurt–Tokyo 159.8 via Singapore); delay under load on a 100 Mb/s link: queueing waits following Pollaczek–Khinchine, the 99th-percentile ping 14.3 ms at 95% load against 9.8 ms idle; a cut cable rerouted from 7.06 to 8.04 ms, with the loop of chapter 10.
- 14. Wireless. Rayleigh fading against Gaussian noise (at 10 dB: 0.023 against 4 × 10⁻⁶). OFDM on 64 subcarriers through a five-path echo: bit errors 0.023 without a cyclic prefix, 0.0012 with one. MIMO: 5.9, 11.3, 22.1, 44.0 bits/s/Hz at 20 dB for 1, 2, 4, 8 antennas.
- 15. Frontier: programmable, verified, convergent. A verifier finds chapter 13's loop in a mid-update snapshot (two prefixes, London–Amsterdam) and none after convergence; header space analysis, Batfish. In-network telemetry, NetCache, in-network aggregation. BAD GADGET oscillating for ever; stable-paths solvability is NP-complete. Six open problems.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- History: circuit switching; Baran (1964) and Davies; ARPANET (1969, "LO"); Cerf & Kahn (1974); the 1983 flag day.
- Layering and encapsulation (headers nesting, animated); the hourglass; the end-to-end argument (Saltzer, Reed & Clark 1984); Clark's design philosophy (1988).
- Physical layer: Nyquist and Shannon–Hartley C = B log₂(1 + S/N); QAM constellations in noise; fiber and the speed of light; the bandwidth–delay product.
- Link layer: framing and bit stuffing; CRC (callback to Part 28); MAC addresses.
- Multiple access: ALOHA, S = G e^{−2G}, max 1/(2e) (derived); slotted 1/e; CSMA/CD and exponential backoff (Metcalfe 1973); Wi-Fi's CSMA/CA and hidden terminals.
- Bridges and switches; Perlman's spanning tree (1985); VLANs.
- IP: CIDR, NAT, IPv6; fragmentation; ICMP and traceroute's TTL trick.
- Forwarding: longest-prefix match with tries (callback to Part 17); TCAMs; nanoseconds per packet at 400 Gb/s.
- Distance vector = distributed Bellman–Ford (callback to Part 18); count-to-infinity animated; split horizon and poisoned reverse.
- Link state: flooding plus Dijkstra (OSPF); convergence and transient loops.
- BGP: path vector; policy (Gao–Rexford); hijacks (YouTube, 2008, cited); RPKI.
- SDN and programmable data planes (OpenFlow, P4).
- Our internet: Pebbles on simulated links and routers; count-to-infinity and traceroute in the simulation.
- Wireless and cellular: fading, OFDM (FFT callback), MIMO capacity. Outro.
Computed: ALOHA, slotted ALOHA and CSMA against their formulas; QAM error rates against the Shannon limit; LPM
lookups; distance-vector and link-state convergence; a BGP policy example; traceroute in the simulation.
Visuals: envelopes nesting headers; collisions on an ALOHA timeline; noisy constellations; distance-vector tables
counting up; an AS graph.
In practice: subnets and CIDR, BGP at ISPs and clouds, Ethernet and Wi-Fi troubleshooting, traceroute and tcpdump.
Reading: Kurose & Ross, Computer Networking: A Top-Down Approach; Peterson & Davie, Computer Networks: A Systems
Approach; Tanenbaum & Wetherall; Stevens, TCP/IP Illustrated vol. 1; Bertsekas & Gallager, Data Networks;
Varghese, Network Algorithmics; Tse & Viswanath, Fundamentals of Wireless Communication; Baran 1964; Cerf & Kahn
1974; Saltzer, Reed & Clark 1984; Abramson 1970; Metcalfe & Boggs 1976; Clark 1988.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
ALOHA。 推导纯 ALOHA 的吞吐量 S = Ge^{−2G} 与时隙 ALOHA 的 Ge^{−G},以及它们的最大值。
解答
尝试(新帧与重传)构成每帧时间速率为 G 的泊松过程。在 t 时刻开始的帧成功,当且仅当 (t − 1, t + 1) 内没有别的帧 开始,这是长度为 2 的区间:概率 e^{−2G}。所以 S = G e^{−2G};dS/dG = e^{−2G}(1 − 2G) 在 G = 1/2 处为零,此时 S = 1/(2e) ≈ 0.184。时隙 ALOHA 中帧只与同一时隙的帧冲突,区间长度为 1:S = G e^{−G},在 G = 1 处最大,S = 1/e ≈ 0.368。 我们的模拟:G = 0.5 时 0.185,G = 1 时 0.369。
-
CRC 能抓住什么。 证明 CRC-32 能检出所有长度不超过 32 位的突发错误;并证明生成多项式能被 x + 1 整除的 CRC 能检出所有 奇数个比特的错误。
解答
错误不被检出,当且仅当错误多项式 E(x) 是 g(x) 的倍数。从第 i 位开始、长度 L ≤ 32 的突发是 E(x) = x^i B(x), 其中 deg B = L − 1 ≤ 31 且 B(0) = 1。由于 g(0) = 1,g 与 x 互素,所以 g | x^i B 推出 g | B,而 B ≠ 0 的次数小于 32, 不可能。若 (x + 1) | g,则 g 的每个倍数在 x = 1 处为零;而有奇数项的错误满足 E(1) = 1。(CRC-32 自己的生成多项式有 15 项, 不能被 x + 1 整除;但它在以太网帧的长度内汉明距离为 4,所以能抓住其中所有 1、2、3 位的错误。)
-
距离向量会收敛。 证明在代价为正且没有变化时,同步距离向量至多 n − 1 轮就得到最短距离。
解答
对 k 归纳:第 k 轮后,D_x(y) 是 x 到 y 至多 k 条链路的最便宜路径的代价(第 0 轮只有 x 自己)。第 k + 1 轮计算 对邻居 v 取 c(x, v) + D_v(y) 的最小值,而至多 k + 1 条链路的最便宜路径,正是先到某个 v 的一条链路、再接从 v 出发至多 k 条链路的最便宜路径。代价为正时最短路径是简单路径,至多 n − 1 条链路;第 n − 1 轮后所有 D 都准确,下一轮什么也不变。我们 的六节点例子 4 轮稳定,等于其最长的最短路径。
-
水平分割的局限。 证明水平分割能阻止所有两节点环,却不能阻止三节点环,并给出计数的例子。
解答
两个节点要成环,只能是 A 到 y 的路由经过 B、B 的经过 A;有了水平分割,A 永远不会把经过 B 的路由告诉 B,所以 B 不能采纳它,反之亦然。取三角形 A、B、C,D 挂在 C 上,切断 C–D。A 和 B 都经 C 到达 D,所以都不向 C 通告 D,C 立刻知道 D 不可达。但 B 告诉 A“D 距离 2”(B 的路由经过 C 而不是 A),A 也这样告诉 B,于是双方都以 3 采纳对方。下一轮 A 的路由经过 B,所以 A 可以通告给 C:C 以 4 经 A 采纳。再下一轮 B 从 C 学到 5……数值绕着三节点的环每轮加一,正是我们的表 (A, B, C) = (3, 3, ∞)、(∞, ∞, 4)、(∞, 5, ∞)……,15 轮后到达 16。
-
动手:在我们的互联网里加上 RIP。 给模拟器加上 RIP:周期性的距离向量作为真实的分组;切断一条链路,看分组在计数期间 打转。
解答
给每个路由器一个 UDP 520 端口的处理函数。每隔周期 T(RIP 中为 30 秒;这里 1 秒就够)向每个邻居发送一个分组, 列出每条路由的(前缀,度量),按需应用水平分割;收到后,用 min(16, c + m) 更新路由,并记下邻居和超时(RIP 中为 180 秒)。 转发数据分组时用 RIP 的表而不是
compute_tables。在三路由器的直线上取 T = 1 秒,切断 B–C 后,去往 C 的分组在 A 与 B 之间来回,直到 TTL 耗尽,持续约 15 个周期,之后以“无路由”被丢弃;有水平分割时,从第一个周期起就被丢弃。触发更新(一有变化 立即发送)把普通的计数从 15 个周期缩短到约 15 个往返时间。 -
★ 研究:无环的重新收敛。 单条链路故障后,找出一种路由器更新顺序,使得没有任何分组打转,并求这种调度所需的最少轮数。
已知的情况与入手的方法。 在第十章里,阿姆斯特丹(紧邻故障)先于伦敦(远一跳)更新,两者形成了环。把顺序反过来,伦敦先 更新,就只剩丢包:我们的
ls_reconverge报告每一时刻都没有环。这就是 oFIB 规则(Francois 与 Bonaventure,2007):对于 断开的链路,一个路由器只有在所有通过它到达故障链路的路由器都已更新之后,才能安装新表,也就是按朝向故障链路的反向最短路径树 的深度从大到小更新;对于恢复的链路则相反。每一层深度是一轮,所以调度的轮数等于树的深度;能否更少,以及如何调度同时发生的 多个变化,就难多了:对任意的转发变化,判定是否存在 k 轮的无环调度是 NP 难的(Ludwig、Marcinkowski 与 Schmid,2015)。 开放的是:对最短路径路由实际产生的变化,轮数的紧界;以及既无环又无黑洞的调度。我们的验证器可以逐状态检查任何候选调度。
Build the film
python -m videos.cs.cs36.compute # the part's numbers, into .cache/cs36
python tools/build.py cs36 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs36 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs36. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs36.compute
python -m unittest tests.test_cs36_net
python tools/build.py cs36