计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

15Network Layers and Protocols

A message leaves a laptop, cut into packets. On its way it crosses a home network, a provider’s network, a cable under the sea and two more networks at the other end, and some of these lose a packet now and then. Yet the message arrives whole, in order, and only once. No single network does this: each does one small job, and a few agreed rules, stacked on one another, do the rest.

This chapter takes those rules apart: the layers and the headers each one adds, the addresses and masks that tell which machines share a network, the tables that routers read to send a packet on, and a protocol that makes a lossy line reliable, which the weekend problem then pushes to its limit on a long cable.

Two network switches with their cables plugged in: each cable joins one machine to the switch, which passes each message on to the cable of its receiver. Photograph: ShakataGaNai, CC BY-SA 3.0.
Two network switches with their cables plugged in: each cable joins one machine to the switch, which passes each message on to the cable of its receiver. Photograph: ShakataGaNai, CC BY-SA 3.0.

You already know

Data crosses a network in packets, each with a packet header that holds, among other things, the addresses of its sender and of its receiver. An IP address names a machine on the internet; routers pass packets from network to network; the domain name system turns names into addresses; a client asks and a server answers (Book 1, grade 8). HTTP is a protocol, and a port number names a program on a machine (chapter 8). A mask keeps some bits of a number with an AND (chapter 3).

15.1 Layers and headers

A protocol fixes the format of the messages and the dialogue: who speaks first, what may answer what. HTTP is one, but it says nothing of how its bytes cross the cable. That job is split among several protocols, stacked.

Definition 15.1 (Layer, encapsulation)

A network’s protocols are organised in layers, each using the service of the layer below and offering one to the layer above: the application layer (HTTP, for instance), the transport layer, which links two programs, the network layer, which carries packets from machine to machine across networks, and the link layer, which carries frames across one cable or one radio link. Each layer adds its own header in front of what it receives from above: this is encapsulation.

Encapsulation. Going down, each layer puts its header (T, N, L) in front of what the layer above gives it; going up at the receiver, each layer reads its own header and removes it.
Encapsulation. Going down, each layer puts its header (T, N, L) in front of what the layer above gives it; going up at the receiver, each layer reads its own header and removes it.

The program below builds the three headers around an HTTP request. They are toy headers, cut down to the addresses and port numbers; real ones hold more fields, as the next section shows.

"""Each layer wraps what the layer above gives it in its own header (toy headers)."""
import ipaddress


def transport(data, src_port, dst_port):
    return src_port.to_bytes(2, "big") + dst_port.to_bytes(2, "big") + data


def network(segment, src, dst):
    return ipaddress.ip_address(src).packed + ipaddress.ip_address(dst).packed + segment


def mac(text):
    return bytes.fromhex(text.replace(":", ""))


def link(packet, src_mac, dst_mac):
    return mac(dst_mac) + mac(src_mac) + bytes([0x08, 0x00]) + packet


def show(name, data, header):
    print(f"{name:12}{data[:header].hex(' '):42}| {len(data) - header} bytes inside")


message = b"GET / HTTP/1.1\r\n\r\n"
segment = transport(message, 49152, 80)
packet = network(segment, "192.0.2.10", "198.51.100.7")
frame = link(packet, "02:00:00:00:00:0a", "02:00:00:00:00:01")
show("link", frame, 14)
show("network", packet, 8)
show("transport", segment, 4)
print(f"{'application':12}{message}")
print("frame:", len(frame), "bytes, of which", len(frame) - len(message), "of headers")
Listing 15.1. Three layers wrap a request, each in its own header. code/grade-11/04-network-protocols/listings/encapsulate.py
$ python encapsulate.py
link        02 00 00 00 00 01 02 00 00 00 00 0a 08 00 | 30 bytes inside
network     c0 00 02 0a c6 33 64 07                   | 22 bytes inside
transport   c0 00 00 50                               | 18 bytes inside
application b'GET / HTTP/1.1\r\n\r\n'
frame: 44 bytes, of which 26 of headers
Output 15.1. Each line shows a header in hexadecimal and the size of what it wraps. c0 00 00 50 are the ports 4915249152 and 8080; c0 00 02 0a is 192.0.2.10.

A router opens the frame, reads the network header to choose where the packet goes next, and puts it in a new frame for the next link: the link header changes at each step, the network header travels from end to end, and the transport header is read only by the two machines at the ends.

15.2 Addresses and the network mask

An IP address of the version used here, IPv4, has 3232 bits, written as four bytes in decimal separated by dots: 192.0.2.10 is 11000000 00000000 00000010 0000101011000000\ 00000000\ 00000010\ 00001010. Its first bits name a network, the rest a machine in that network.

Definition 15.2 (Network mask, prefix)

The network mask of a network is a 3232-bit number made of ones followed by zeros: the bits under the ones are the network part of each address, the others the machine’s part. The number nn of ones is the prefix length, written after a slash: 192.0.2.0/24 is the network whose addresses share their first 2424 bits with 192.0.2.0. Two machines are on the same network when the AND of their address with the mask gives the same result.

The addresses in this chapter’s examples come from three blocks set aside for documentation, 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24, which no real machine uses. Homes and schools use other reserved blocks inside their own networks, such as 192.168.0.0/16 and 10.0.0.0/8, which never appear on the internet itself.

$ python same_network.py
192.0.2.0/26 mask 255.255.255.192 -> 64 addresses
first 192.0.2.0 last 192.0.2.63
192.0.2.37 in 192.0.2.0/26 : True
192.0.2.64 in 192.0.2.0/26 : False
198.51.100.7 in 192.0.2.0/26 : False
192.0.2.37/24 belongs to the network 192.0.2.0/24
Output 15.2. Python’s ipaddress module knows masks and prefixes. A /26 leaves 66 bits to the machines: 26=642^6 = 64 addresses.
"""The network part of an address, by hand: an AND with the mask."""
import ipaddress


def to_int(dotted):
    a, b, c, d = (int(x) for x in dotted.split("."))
    return (a << 24) | (b << 16) | (c << 8) | d


def to_dotted(n):
    return ".".join(str((n >> shift) & 255) for shift in (24, 16, 8, 0))


def mask(prefix):
    return (2**32 - 1) ^ (2**(32 - prefix) - 1)  # prefix ones, then zeros


address, prefix = "192.0.2.37", 26
print(f"address {to_int(address):032b}")
print(f"mask    {mask(prefix):032b}  = {to_dotted(mask(prefix))}")
network = to_int(address) & mask(prefix)
print(f"AND     {network:032b}  = {to_dotted(network)}")
print("module:", ipaddress.ip_interface(f"{address}/{prefix}").network)
Listing 15.2. The network part by hand: a mask built from the prefix, then an AND. code/grade-11/04-network-protocols/listings/mask_bits.py
$ python mask_bits.py
address 11000000000000000000001000100101
mask    11111111111111111111111111000000  = 255.255.255.192
AND     11000000000000000000001000000000  = 192.0.2.0
module: 192.0.2.0/26
Output 15.3. The AND keeps the first 2626 bits and clears the others; the module agrees.

The first address of a network, all machine bits 00, names the network itself, and the last, all machine bits 11, is used to reach every machine of the network at once: a /26 leaves 6262 addresses for machines.

The header of an IPv4 packet, 32 bits per row, 20 bytes without options. Each router lowers the time to live by one and drops the packet at zero, so a packet lost in a loop does not travel for ever.
The header of an IPv4 packet, 3232 bits per row, 2020 bytes without options. Each router lowers the time to live by one and drops the packet at zero, so a packet lost in a loop does not travel for ever.

Thirty-two bits give about four billion addresses, too few for every device in the world. The newer version, IPv6, uses 128128-bit addresses, written in hexadecimal; both versions run side by side on the internet.

15.3 A routing table read by hand

Definition 15.3 (Routing table, next hop, default route)

A router’s routing table lists networks, each written with its prefix, and for each the next hop: the neighbouring router to pass the packet to, or “direct” when the network is connected to the router itself. When several lines contain the destination, the router takes the one with the longest prefix, the most precise. The line 0.0.0.0/0, which contains every address, is the default route: it is used when no other line fits.

Router A and its table. The /24 line through B also contains the addresses of C’s network; for those, the /25 line through C is longer, so it wins.
Router A and its table. The /24 line through B also contains the addresses of C’s network; for those, the /25 line through C is longer, so it wins.
"""A router's table, read by longest prefix match."""
import ipaddress

TABLE = [  # destination, next hop
    ("192.0.2.0/24", "direct, port 1"),
    ("198.51.100.0/24", "router B"),
    ("198.51.100.128/25", "router C"),
    ("0.0.0.0/0", "router D (default)"),
]


def lookup(address):
    address = ipaddress.ip_address(address)
    best = None
    for dest, hop in TABLE:
        net = ipaddress.ip_network(dest)
        if address in net and (best is None or net.prefixlen > best[0].prefixlen):
            best = (net, hop)
    return best


for a in ["192.0.2.99", "198.51.100.7", "198.51.100.200", "203.0.113.5"]:
    net, hop = lookup(a)
    print(f"{a:16} matches {str(net):19} -> {hop}")
Listing 15.3. Router A’s table, and the longest prefix match. code/grade-11/04-network-protocols/listings/route_lookup.py
$ python route_lookup.py
192.0.2.99       matches 192.0.2.0/24        -> direct, port 1
198.51.100.7     matches 198.51.100.0/24     -> router B
198.51.100.200   matches 198.51.100.128/25   -> router C
203.0.113.5      matches 0.0.0.0/0           -> router D (default)
Output 15.4. Two lines contain 198.51.100.200; the /25 is longer. Nothing but the default route contains 203.0.113.5.

Each router decides only the next hop. The packet’s whole route is never written anywhere: it is the chain of these local choices, which is why the tables of neighbouring routers must agree, and why routers exchange what they know with one another.

15.4 Reliable delivery over an unreliable network

Packets get lost: a router whose queue is full drops what arrives, a radio link loses a frame to noise. The network layer does not repair this. The two ends repair it themselves.

Definition 15.4 (Acknowledgement, timeout, retransmission)

An acknowledgement is a short message by which the receiver tells the sender that a packet arrived. If no acknowledgement comes back within a set time, the timeout, the sender sends the packet again: a retransmission.

Retransmission brings a new trap. If the packet arrived but its acknowledgement was lost, the sender sends it again and the receiver gets it twice. The receiver must tell a new packet from a copy.

Definition 15.5 (Alternating-bit protocol)

In the alternating-bit protocol, each packet carries one bit, 00 for the first, 11 for the next, 00 again, and so on. The sender sends a packet until an acknowledgement with its bit comes back, then moves to the next packet with the other bit. The receiver acknowledges every packet with the bit it carries, and keeps it only if its bit is the one expected; a packet with the other bit is a copy, and is dropped.

History — A note of two pages

The alternating-bit protocol was published in May 1969 by K. A. Bartlett, R. A. Scantlebury and P. T. Wilkinson, in a note of two pages on reliable transmission over links that lose messages.

The simulation below uses a channel that loses each item with a set probability, drawn from a seeded generator, so that every run loses the same packets.

"""A channel that loses some of what it carries, at random but reproducibly."""
import random


class Channel:
    def __init__(self, loss, seed):
        self.loss = loss                  # the probability of losing each item
        self.rng = random.Random(seed)

    def carry(self, item):
        """Return the item, or None if it was lost on the way."""
        return None if self.rng.random() < self.loss else item
Listing 15.4. A lossy channel, reproducible thanks to its seed. code/grade-11/04-network-protocols/listings/lossy_channel.py
"""The alternating-bit protocol over two lossy channels (data one way, acks back)."""
from lossy_channel import Channel


def run(messages, data_line, ack_line):
    sent_bit, expected, delivered, sends = 0, 0, [], 0
    for m in messages:
        while True:  # send m until its acknowledgement comes back
            sends += 1
            print(f"send ({sent_bit}, {m})", end="  ")
            frame = data_line.carry((sent_bit, m))
            if frame is None:
                print("lost; timeout")
                continue
            bit, data = frame
            if bit == expected:
                delivered.append(data)
                expected = 1 - expected
                print("delivered", end="  ")
            else:
                print("duplicate dropped", end="  ")
            ack = ack_line.carry(bit)   # the receiver acknowledges every frame
            if ack is None:
                print("ack lost; timeout")
                continue
            print(f"ack {ack}")
            if ack == sent_bit:
                sent_bit = 1 - sent_bit
                break
    return delivered, sends


if __name__ == "__main__":
    got, sends = run(["a", "b", "c", "d"], Channel(0.3, seed=10), Channel(0.3, seed=3))
    print("received", got, "after", sends, "sends")
Listing 15.5. The alternating-bit protocol: the sender’s loop and the receiver’s test. code/grade-11/04-network-protocols/listings/alternating_bit.py
$ python alternating_bit.py
send (0, a)  delivered  ack lost; timeout
send (0, a)  duplicate dropped  ack 0
send (1, b)  delivered  ack 1
send (0, c)  lost; timeout
send (0, c)  delivered  ack 0
send (1, d)  delivered  ack 1
received ['a', 'b', 'c', 'd'] after 6 sends
Output 15.5. A lost acknowledgement makes a copy, which the receiver drops; a lost packet is simply sent again. Four messages arrive, once each, in order.
Time flows downwards; a × marks a loss. A lost acknowledgement (top) and a lost packet (middle): in both cases the sender’s timeout sends the packet again, and the bit lets the receiver drop the copy.
Time flows downwards; a ×\times marks a loss. A lost acknowledgement (top) and a lost packet (middle): in both cases the sender’s timeout sends the packet again, and the bit lets the receiver drop the copy.

Waiting for each acknowledgement before sending on, stop and wait, has a cost: while the packet and its acknowledgement travel, the line is idle. If sending a packet takes a time TT and the round trip a time RR, the line is busy a fraction T/(T+R)T / (T + R) of the time.

"""Stop and wait: the sender is busy for T, then idle for one round trip."""

PACKET = 1500 * 8  # bits


def utilisation(rate, rtt):
    t = PACKET / rate              # time to put the packet on the line
    return t / (t + rtt)


for name, rate, rtt in [("one room", 100e6, 0.0002), ("one town", 100e6, 0.002),
                        ("one country", 1e9, 0.02), ("faster line", 10e9, 0.02)]:
    u = utilisation(rate, rtt)
    print(f"{name:12} {rate / 1e6:>6.0f} Mbit/s  rtt {rtt * 1000:>4} ms  "
          f"busy {u:7.3%}  useful {u * rate / 1e6:6.2f} Mbit/s")
Listing 15.6. The share of time stop and wait keeps the line busy. code/grade-11/04-network-protocols/listings/throughput.py
$ python throughput.py
one room        100 Mbit/s  rtt  0.2 ms  busy 37.500%  useful  37.50 Mbit/s
one town        100 Mbit/s  rtt  2.0 ms  busy  5.660%  useful   5.66 Mbit/s
one country    1000 Mbit/s  rtt 20.0 ms  busy  0.060%  useful   0.60 Mbit/s
faster line   10000 Mbit/s  rtt 20.0 ms  busy  0.006%  useful   0.60 Mbit/s
Output 15.6. On long links stop and wait wastes almost all the line. A ten times faster line does not help: the round trip is the limit.

15.5 Ports and the transport layer

An IP address names a machine; a port number, 1616 bits, names a program on it. Ports 00 to 10231023 are the system ports, given to well-known services, such as 8080 for HTTP and 443443 for HTTPS; a client’s own port is usually taken from the top of the range, 4915249152 to 6553565535, as in the frame of the first section.

Definition 15.6 (TCP, UDP)

The internet’s two main transport protocols are TCP, which gives two programs a reliable stream of bytes, in order and without copies, by numbering the bytes, acknowledging them and sending again what is lost, and UDP, which sends single datagrams with no acknowledgement, so that they may be lost, duplicated or arrive out of order. A TCP header has at least 2020 bytes, a UDP header 88.

TCP’s reliability has a price in time, since a lost packet waits for its retransmission and the bytes behind it wait too. A video call prefers UDP: a lost image is better skipped than shown late. Neither protocol promises when data arrives; reliable does not mean fast.

Definition 15.7 (Peer-to-peer network)

In a peer-to-peer network, every machine is both client and server: each asks the others for data and serves what it has, with no central server.

Before a program can send anything to library.example, the name must become an address. A machine first looks in a small local table, then, if the name is not there, asks the domain name system. The names ending in .example are reserved for examples like this one.

"""Names to addresses from a local table, in the format of a hosts file."""
HOSTS = """\
# address       names
192.0.2.10      library.example  library
192.0.2.11      mail.example
198.51.100.7    town.example
"""


def parse(text):
    table = {}
    for line in text.splitlines():
        line = line.split("#")[0].strip()      # a # starts a comment
        if line:
            address, *names = line.split()
            for name in names:
                table[name] = address
    return table


table = parse(HOSTS)
for name in ["library", "town.example", "school.example"]:
    print(name, "->", table.get(name, "unknown here: ask the name system"))
Listing 15.7. A local table of names, in the format of the hosts file most systems keep. code/grade-11/04-network-protocols/listings/hosts_lookup.py
$ python hosts_lookup.py
library -> 192.0.2.10
town.example -> 198.51.100.7
school.example -> unknown here: ask the name system
Output 15.7. Two names are found locally; the third would go to the name system.

15.6 Exercises

Exercise 15.1 ★

Give the network address of 192.168.10.37/24.

Solution

Solution of Exercise 15.1.

The mask 255.255.255.0 keeps the first three bytes and clears the last: 192.168.10.0.

Exercise 15.2 ★

How many addresses does a /26 network contain? How many machines can it hold, the first and last addresses set apart?

Solution

Solution of Exercise 15.2.

32−26=632 - 26 = 6 bits for the machines: 26=642^6 = 64 addresses. Without the first (the network) and the last (all the machines at once), 6262 machines.

Exercise 15.3 ★

With router A’s table, where does a packet for 198.51.100.130 go? For 198.51.100.127?

Solution

Solution of Exercise 15.3.

198.51.100.130 is in 198.51.100.0/24 and in 198.51.100.128/25, which holds .128 to .255; the /25 is longer: router C. 198.51.100.127 is only in the /24: router B.

Exercise 15.4 ★

In what order do the headers come in a frame, from its first byte? Which of them does a router read and replace?

Solution

Solution of Exercise 15.4.

The link header, then the network header, then the transport header, then the data. A router reads the link header, which brought the frame to it, and the network header, to choose the next hop; it replaces the link header with one for the next link, and in the network header it only lowers the time to live. It does not read the transport header.

Exercise 15.5 ★

Write a function same_network(a, b, prefix) that tells whether two addresses, given as dotted strings, are on the same network, without the ipaddress module’s networks: build the mask, then compare.

Solution

Solution of Exercise 15.5.

def same_network(a, b, prefix):

m = (2**32 - 1) ^ (2**(32 - prefix) - 1)

x = int(ipaddress.ip_address(a))

y = int(ipaddress.ip_address(b))

return x & m == y & m

The module only turns the dotted strings into numbers; to_int of the chapter would do as well. The precedence of & is higher than that of ==, so no brackets are needed.

Exercise 15.6 ★★

A student computes the network part of 192.0.2.37/26 with an OR instead of an AND, and gets 255.255.255.229. Explain what the OR did, bit by bit.

Solution

Solution of Exercise 15.6.

An OR with 11 gives 11, an OR with 00 leaves the bit: the 2626 ones of the mask became ones, and the last 66 bits of the address stayed. 37=10010137 = 100101 in binary, so the last byte is 11100101=22911100101 = 229 and the first three are 255255. The result keeps the machine’s part and loses the network’s, exactly the opposite of what was wanted.

Exercise 15.7 ★★

Write a function lookup(table, address) that takes a table as a list of pairs, prefix and next hop, and returns the next hop by longest prefix match, or None if no line contains the address.

Solution

Solution of Exercise 15.7.

def lookup(table, address):

a = ipaddress.ip_address(address)

fits = [(ipaddress.ip_network(d), hop) for d, hop in table

if a in ipaddress.ip_network(d)]

if not fits:

return None

return max(fits, key=lambda f: f[0].prefixlen)[1]

The tests check that it agrees with the chapter’s lookup on its four addresses, and that it returns None once the default route is removed.

Exercise 15.8 ★★

A program sends a message of 100100 bytes over TCP and IPv4 on an Ethernet link, whose header has 1414 bytes: two addresses of 66 bytes and a type of 22. How many bytes leave the machine, and what share of them are headers?

Solution

Solution of Exercise 15.8.

100+20+20+14=154100 + 20 + 20 + 14 = 154 bytes: 2020 of TCP, 2020 of IPv4, 1414 of Ethernet. The headers are 54/15454 / 154, about 3535 percent. Small messages pay a high share of headers.

Exercise 15.9 ★★

The alternating-bit protocol sends the messages x and y. The first packet sent is lost; the first acknowledgement of y is lost; nothing else is. Write the trace, in the format of the chapter’s output, and count the sends.

Solution

Solution of Exercise 15.9.

send (0, x) lost; timeout

send (0, x) delivered ack 0

send (1, y) delivered ack lost; timeout

send (1, y) duplicate dropped ack 1

Four sends for two messages.

Exercise 15.10 ★★

A receiver keeps every packet without checking its bit. Show, with a lost acknowledgement, what goes wrong.

Solution

Solution of Exercise 15.10.

The packet (0, a) arrives and is kept; its acknowledgement is lost. The sender’s timeout sends (0, a) again, and this receiver keeps it too: the application receives a twice, as the function receiver of exercises/net_ex.py shows when called with check_bit=False.

Exercise 15.11 ★★

A line of 1010 Mbit/s sends packets of 10001000 bytes by stop and wait, with a round trip of 3.23.2 ms. What share of the time is the line busy, and what is the useful rate?

Solution

Solution of Exercise 15.11.

T=8000/107=0.8T = 8000 / 10^7 = 0.8 ms. The busy share is 0.8/(0.8+3.2)=0.20.8 / (0.8 + 3.2) = 0.2, that is 2020 percent, and the useful rate is 0.2×10=20.2 \times 10 = 2 Mbit/s.

Exercise 15.12 ★★★

The channel may lose packets and acknowledgements, but never reorders them and never invents them. Show that the receiver of the alternating-bit protocol keeps every message exactly once, in order. Consider what the receiver may see while the sender is sending one message.

Solution

Solution of Exercise 15.12.

Write bkb_k for the bit of message kk: 00 when kk is odd, 11 when it is even, so bk+1=bk−1b_{k+1} = b_{k-1}. We show that the following holds each time the sender starts on message kk: the receiver has kept m1,…,mk−1m_1, \dots, m_{k-1} and nothing else, it expects the bit bkb_k, and everything still on its way, in either direction, carries the bit bk−1b_{k-1}. It holds for k=1k = 1, with nothing on the way.

While the sender sends mkm_k, the data channel holds, in this order, some old copies of mk−1m_{k-1} and then copies of mkm_k; since the channel never reorders, every old copy arrives, or is lost, before any copy of mkm_k. The old copies have the bit bk−1b_{k-1}, not the one expected: they are dropped, and only acknowledged with bk−1b_{k-1}. The first copy of mkm_k that arrives has the expected bit: mkm_k is kept, once, and the receiver now expects bk+1=bk−1b_{k+1} = b_{k-1}; later copies of mkm_k have the bit bkb_k and are dropped. On the way back, the sender ignores the acknowledgements bk−1b_{k-1}. An acknowledgement bkb_k is sent only after a copy of mkm_k arrived, so when the first one reaches the sender, mkm_k has been kept; the sender moves on to mk+1m_{k+1}. At that moment every acknowledgement sent earlier, with bk−1b_{k-1}, has arrived or been lost, and every old copy of mk−1m_{k-1} too: what remains on the way carries bkb_k. The statement holds for k+1k + 1.

So each message is kept exactly once, in order, as long as each packet, sent again and again, eventually gets through.

Exercise 15.13 ★★★

With a window of ww, the sender may have up to ww packets sent and not yet acknowledged. Write window_time(n, w, rtt): time is counted in ticks, one packet is sent per tick at most, and the acknowledgement of a packet sent at tick tt arrives at tick t+1+rttt + 1 + \mathit{rtt}. Return the tick at which the last acknowledgement arrives, with no loss. Compare w=1w = 1, 22 and 55 for n=10n = 10, rtt=4\mathit{rtt} = 4.

Solution

Solution of Exercise 15.13.

def window_time(n, w, rtt):

acks, tick, sent = [], 0, 0

while sent < n:

acks = [a for a in acks if a > tick]

if len(acks) < w:

acks.append(tick + 1 + rtt)

sent += 1

tick += 1

return max(acks)

The list holds the arrival ticks of the acknowledgements still awaited. For n=10n = 10 and rtt=4\mathit{rtt} = 4: 5050 ticks with w=1w = 1, each packet taking 55; 2626 with w=2w = 2; 1414 with w=5w = 5, which is n+rttn + \mathit{rtt}: with 55 packets in flight, the acknowledgement of the first comes back just when the sender wants to send the sixth, and the sender never waits.

Exercise 15.14 ★★★

Suppose now the channel may delay a packet and deliver it after later ones. Find a sequence of events where the alternating-bit receiver keeps a message twice and loses another.

Solution

Solution of Exercise 15.14.

The sender sends (0, a), which the channel holds back. The timeout sends (0, a) again; this copy arrives, is kept and acknowledged. The sender sends (1, b), which is kept and acknowledged, then (0, c). The old copy of (0, a) now arrives before (0, c): its bit is the one expected, so the receiver keeps a a second time and acknowledges it with 00. Then (0, c) arrives with a bit that is no longer expected and is dropped as a copy; the sender, seeing an acknowledgement 00, believes c arrived and goes on. The receiver has kept a, b, a, and c is lost.

Exercise 15.15 ★★★

Split 192.0.2.0/24 into four networks of equal size. Give each one’s prefix, its first and last addresses, and the number of machines it can hold.

Solution

Solution of Exercise 15.15.

Four networks need 22 more bits of prefix: four /26, each of 6464 addresses and 6262 machines.

  • 192.0.2.0/26, from .0 to .63;
  • 192.0.2.64/26, from .64 to .127;
  • 192.0.2.128/26, from .128 to .191;
  • 192.0.2.192/26, from .192 to .255.

15.7 Problem: Stop and Wait Across the Sea

Problem 15.1

Weekend problem — how many packets in flight fill a long line

A cable of 60006000 km under the sea joins two cities. It carries 11 Gbit/s, and its signals travel at 200 000200\,000 km/s. Packets have 15001500 bytes. The acknowledgements are so short that their own sending time is neglected, and so is the time the machines take to answer. The program below computes what the line delivers when the sender may have ww packets in flight before it must wait.

Part I — The line.

  1. How long does the sender take to put one packet on the line?
  2. How long does a signal take to cross the cable one way? What is the round trip?
  3. Why may the acknowledgement’s own sending time be neglected here?
  4. While the first bit crosses the cable, how many bits has the sender put behind it at full rate?

Part II — Stop and wait.

  1. With stop and wait, how long passes between the start of one packet and the start of the next?
  2. How many packets per second does this make, and what useful rate?
  3. How long would a file of 11 GB, 8×1098 \times 10^9 bits, take to cross?
  4. Check your answers against the line window 1 of the output.

Part III — The busy share.

  1. Explain the formula T/(T+R)T / (T + R) for stop and wait.
  2. Compute it here, as a percentage and as “one in how many”.
  3. The line is replaced by one of 1010 Gbit/s. What happens to the busy share, and to the useful rate?
  4. Name two changes that would raise the useful rate of stop and wait, and say why neither helps much here.

Part IV — The window.

  1. Explain why, with a window of ww, the busy share is the smaller of 11 and wT/(T+R)wT / (T + R).
  2. Check the line window 1000 of the output by hand.
  3. Find the smallest window that keeps the line busy all the time, and check it against the program.
  4. How many bytes are in flight, sent and not yet acknowledged, at full rate? The sender must keep them all, in case it has to send them again: why?
  5. Why can the packets no longer carry a single bit, as in the alternating-bit protocol?
  6. If the cable lost one packet in a thousand, about how many losses would happen per second at full rate?
  7. The window field of a TCP header has 1616 bits and counts bytes; a larger window needs an extension that shifts it. Without that extension, how many full packets fit in the largest window, and what busy share would it allow on this cable?
  8. State the result: the busy share of stop and wait on this cable, and the window that fills it.
Solution

Solution of Problem 15.1.

1. 1500×8=12 0001500 \times 8 = 12\,000 bits at 10910^9 bit/s: T=12T = 12 µs.

2. 6×106/(2×108)=0.036 \times 10^6 / (2 \times 10^8) = 0.03 s, so 3030 ms one way and R=60R = 60 ms there and back.

3. An acknowledgement of a few tens of bytes takes well under a microsecond to send, nothing beside 6060 ms.

4. 109×0.03=3×10710^9 \times 0.03 = 3 \times 10^7 bits, 3030 Mbit, or 25002500 packets.

5. T+R=60.012T + R = 60.012 ms: the packet is sent, crosses, and the acknowledgement comes back.

6. 1/0.060012≈16.661 / 0.060012 \approx 16.66 packets per second, so about 16.66×12 000≈199 96016.66 \times 12\,000 \approx 199\,960 bit/s: 0.20.2 Mbit/s.

7. 8×109/199 960≈40 0088 \times 10^9 / 199\,960 \approx 40\,008 s, about 1111 hours, on a line that could do it in 88 seconds.

8. The line window 1 prints a busy share of 0.02000.0200 percent and 0.200.20 Mbit/s.

9. In each cycle of length T+RT + R, the line is busy only during the TT it takes to send the packet; it is idle while the packet crosses and while the acknowledgement comes back.

10. 12/60 012≈0.000212 / 60\,012 \approx 0.0002, that is 0.02000.0200 percent, or one moment in 60 012/12=500160\,012 / 12 = 5001.

11. TT falls to 1.21.2 µs, so the busy share falls to 1.2/60 001.21.2 / 60\,001.2, about 0.0020.002 percent, and the useful rate stays at 12 000/0.0600012≈0.212\,000 / 0.0600012 \approx 0.2 Mbit/s. The round trip, not the line’s rate, is the limit.

12. Larger packets, or a shorter round trip. The distance and the speed of the signal are fixed, and a packet ten times larger would only make the rate ten times larger, still a fraction of a percent of the line; a lost large packet also costs more to send again.

13. The sender sends ww packets one after the other, which takes wTwT. The first acknowledgement comes back T+RT + R after the start, and each following one a time TT later, freeing a place for one more packet. If wT≥T+RwT \ge T + R, the next acknowledgement always arrives before the window is used up and the line never rests; otherwise it works wTwT in each cycle of T+RT + R.

14. 1000×12/60 012≈0.199961000 \times 12 / 60\,012 \approx 0.19996, so 19.99619.996 percent and 199.96199.96 Mbit/s, as printed.

15. w≥(T+R)/T=60 012/12=5001w \ge (T + R) / T = 60\,012 / 12 = 5001: the smallest window is 50015001 packets. The program finds the same, with 50005000 giving 99.9899.98 percent.

16. 109×0.06=6×10710^9 \times 0.06 = 6 \times 10^7 bits, 7.57.5 MB, about 50005000 packets. Any of them may be lost, and until its acknowledgement arrives, the sender cannot know; it must be able to send it again.

17. With thousands of packets in flight, a single bit cannot tell which packet an acknowledgement is for, nor tell a copy from one of the many new packets: the numbers must be large enough to tell apart all the packets in flight.

18. At full rate, 109/12 000≈83 33310^9 / 12\,000 \approx 83\,333 packets per second: about 8383 losses per second, each one to detect and repair while the rest flows on.

19. 65 535/1500≈43.765\,535 / 1500 \approx 43.7, so 4343 full packets. Busy share 43×12/60 012≈0.008643 \times 12 / 60\,012 \approx 0.0086, under 11 percent, about 8.68.6 Mbit/s. On such a line the extension is needed.

20. On this cable, stop and wait keeps the line busy 0.02000.0200 percent of the time, one moment in 50015001, for 0.20.2 Mbit/s out of 11 Gbit/s; a window of 50015001 packets, 7.57.5 MB in flight, fills it.

本章定义的术语

在术语表中查看全部 1050 个术语