In this chapter, we go into detail about Linux networking. In modern environments, the network stack that Linux provides is an essential component. Without it, few things are possible. Whether you want to access an instance in your cloud provider, browse the web, or install a new app, you need connectivity, and you need a way to interact with it.

We’ll first have a look at common network terms, from the hardware level all the way up to user-facing components such as HTTP and SSH. We’ll also discuss the network stack, protocols, and interfaces. Specifically, we’ll spend time on the naming center piece of the web and the wider internet, the so-called Domain Name System (DNS). Interestingly, this system is found not only in wide-area deployments but is also a central component used for service discovery in container environments such as Kubernetes.

Next, we’ll look at application layer network protocols and tooling. This includes file sharing, the web, networked filesystems, and other methods to share data over the network.

In the last part of the chapter, we’ll review some advanced network topics, from geomapping to managing time over the network.

To set the expectations for the content in this chapter: you can spend a lot of time with the topic of Linux networking; in fact, entire books are dedicated to the topic. We’ll take a pragmatic stance here, jumping into hands-on topics from an end-user point of view. Admin topics around networking, such as configuration and setup of network devices, are by and large out of scope here.

Now, let’s turn our attention to the networking basics.

Basics

Let’s first discuss why networking is relevant for a number of use cases and define some common network terminology.

In modern environments, networking plays a central role. This ranges from tasks such as installing apps, browsing the web, and viewing mail or social media to working with remote machines (from the embedded system you’re connecting to over a local network to servers that run in data centers of your cloud providers). Given a network’s many moving parts and layers, it can be difficult to figure out if a problem is hardware-related or originates in the software stack.

Another challenge Linux networking addresses comes from abstractions: many of the things we’ll cover in this chapter provide a high-level user interface, making it appear that files or applications that in reality run on a remote machine are accessible or can be manipulated on your local machine. While providing an abstraction that makes remote resources seem to be local is a useful feature, we should not forget that at the end of the day, all of this boils down to bits traveling over the wire and through the air. Keep this in mind when troubleshooting or testing.

Figure 7-1 shows how, on a high level, networking works in Linux. There is some kind of networking hardware, such as Ethernet or wireless cards; then a number of kernel-level components, such as the TCP/IP stack; and finally, in the user space, a range of tools to configure, query, and use networking.

lmlx 0701

Figure 7-1. An overview of Linux networking

Let’s now dive into the TCP/IP stack, the core of networking in Linux.

Tip

Unlike in other areas of Linux, where you need to either consult the source code or hope for properly documented design assumptions behind interfaces and protocols, in the networking space, almost every protocol and interface is based on publicly available specifications. The Internet Engineering Task Force (IETF) makes all of those requests for comments (RFCs) freely available via data​tracker.ietf.org .

Make a habit out of simply reading these RFCs before you get into the details of implementations. Those RFCs are written by practitioners for practitioners and document good practices and how to implement stuff. Don’t be afraid of working through them; you’ll gain a much better understanding about the motivation, use cases, and reasons why things are the way they are.

The TCP/IP Stack

The TCP/IP stack, shown in Figure 7-2 , is a layered network model made of a number of protocols and tools, mostly defined by IETF specs. Each layer must be aware of and able to communicate with only the layers right above and below itself. The data is encapsulated in packets, and each layer typically wraps the data in a header that contains information relevant for its function. So, if an app wants to send data, it would interact directly with the highest layer that would add a header and so on down the stack (the send path). Conversely, if an app wants to receive data, it would arrive at the lowest layer, and each layer in turn would process it based on the header information it finds and pass the payload on to the layer above (the receive path).

lmlx 0702

Figure 7-2. The TCP/IP layers working together to enable communication

Starting at the bottom of the stack, the four layers of the TCP/IP stack are the following:

The link layer

Lowest in the stack, this layer covers the hardware (Ethernet, WiFi) and kernel drivers and focuses on how packets are sent between physical devices. See “The Link Layer” for details.

The internet layer

With the Internet Protocol (IP), this layer focuses on routing; that is, it supports sending packets between machines across networks. We’ll discuss it in “The Internet Layer” .

The transport layer

This layer controls end-to-end communications between (virtual or physical) hosts, with the Transmission Control Protocol (TCP) for session-based, reliable communication and User Datagram Protocol (UDP) for connection-less communication. It mainly deals with how packets are transmitted, including addressing individual services on a machine via ports as well as data integrity. Further, Linux supports sockets as communication endpoints. See “The Transport Layer” .

The application layer

This layer deals with user-facing tooling and apps, such as the web, SSH, and mail. We’ll discuss it in “DNS” and “Application Layer Networking” .

The Internet and OSI

The internet has its roots in a US Department of Defense project started in the 1960s that had the goal to create a communication network that couldn’t easily be destroyed. The internet is a network of networks—that is, many local networks hooked up with a backend infrastructure enabling communication between different systems.

You’ll likely come across the Open Systems Interconnection (OSI) model, a theoretical model of networking that uses seven layers, with the seventh, the top-most layer, being the application layer. The TCP/IP model has only four layers, but the TCP/IP stack is what is used everywhere in practice.

Don’t get confused by the layer numbering. Usually, since the hardware counts as layer 1, the link layer would be 2, the internet layer 3, the transport layer 4, and (for historical reasons, to be OSI model-aligned), the application layer would be 7.

The layering means that the header and the payload of a layer make up the payload for the next layer. For example, looking at Figure 7-2 , the payload in the internet layer is the transport layer header H T and its payload. In other words, the internet layer takes the packet it gets from the transport layer, treats it as an opaque chunk of bytes, and can focus on its function, the routing of the packet to the target machine.

Let’s now work our way up the TCP/IP stack, starting with the lowest layer, the link layer.

The Link Layer

In the link layer of the TCP/IP stack, it’s all about hardware or near-hardware stuff, such as bytes, wires, electromagnetic waves, device drivers, and network interfaces. You’ll come across the following terms in this context:

Ethernet

A family of networking technologies using wires to connect machines; often used in local area networks (LANs).

Wireless

Also known as WiFi, a class of communication protocols and methods that, rather than using wires, uses some electromagnetic waves to transport data.

MAC addresses

Short for media access control , MAC is a unique 48-bit identifier for hardware, used to identify your machine (to be precise, the network interface; see the following term). The MAC address encodes the manufacturer (of the interface) via the organizationally unique identifier (OUI), usually occupying the first 24 bits.

Interface

A network connection. It can be a physical interface (see “Network interface controller” for details) or a virtual (software) interface, like the loopback interface lo .

Equipped with these basics, let’s have a closer look at the link layer.

Network interface controller

One essential piece of hardware equipment is the network interface controller (NIC) , sometimes also called the network interface card . The NIC provides the physical connectivity to a network through either a wired standard—for example, the IEEE 802.3-2018 standard for Ethernet —or one of the many wireless standards from the IEEE 802.11 family . Once part of a network, the NIC turns the digital representation of the bytes you want to send into electrical or electromagnetic signals. The reverse is true for the receive path, where the NIC turns whatever physical signals it receives into bits and bytes that the software can deal with.

Let’s have a look at NICs in action. Traditionally, one would use the (now widely considered deprecated) ifconfig command to query information on the NICs available on the system (we show it here first for educational purposes; in practice, it’s better to use ip , as shown in the next example):

$ ifconfig
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536 
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 7218  bytes 677714 (677.7 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 7218  bytes 677714 (677.7 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500 
        inet 192.168.178.40  netmask 255.255.255.0  broadcast 192.168.178.255
        inet6 fe80::be87:e600:7de7:e08f  prefixlen 64  scopeid 0x20<link>
        ether 38:de:ad:37:32:0f  txqueuelen 1000  (Ethernet)
        RX packets 2398756  bytes 3003287387 (3.0 GB)
        RX errors 0  dropped 7  overruns 0  frame 0
        TX packets 504087  bytes 85467550 (85.4 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

1

The first interface here is lo , the loopback interface with the IP address 127.0.0.1 (see “IPv4” ). The maximum transmission unit (MTU) is the packet size, here 65,536 bytes (with larger sizes meaning higher throughput); for historical reasons, the default for Ethernet was 1,500 bytes, but you can use jumbo frames that are 9,000 bytes in size.

2

The second interface reported is wlp1s0 , with an IPv4 address of 192.168.178.40 assigned. This interface is an NIC and has a MAC address ( ether is 38:de:ad:37:32:0f ). When looking at the flags ( <UP,BROADCAST,RUNNING,MULTICAST> ), it seems to be operational.

For a more modern approach of doing the same thing (querying interfaces and checking on their status), use the ip command . We’ll use this approach most often in this chapter (output edited to fit):

$ ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue 
   state UNKNOWN mode DEFAULT group default qlen 1000
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: wlp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue 
   state UP mode DORMANT group default qlen 1000
    link/ether 38:de:ad:37:32:0f brd ff:ff:ff:ff:ff:ff

1

The loopback interface.

2

My NIC, with a MAC address of 38:de:ad:37:32:0f . Note that the name ( wlp1s0 ) here tells you something about the interface: it’s a wireless interface ( wl ) in PCI bus 1 ( p1 ) and slot 0 ( s0 ). This naming makes the interface names more predictable. In other words, if you had two old-style interfaces (say, eth0 and eth1 ), there was no guarantee that a reboot or adding a new card wouldn’t cause Linux to rename those interfaces.

For both ifconfig and ip link , you might be interested in the meaning of flags such as LOWER_UP or MULTICAST ; these are documented in the netdevice man pages .

Address Resolution Protocol

The Address Resolution Protocol (ARP) maps MAC addresses to IP addresses. In a sense, it bridges the link layer with the layer above it, the internet layer.

Let’s see it in action:

$ arp 
Address                  HWtype  HWaddress           Flags Mask            Iface
mh9-imac.fritz.box       ether   00:25:4b:9b:64:49   C                     wlp1s0
fritz.box                ether   3c:a6:2f:8e:66:b3   C                     wlp1s0

1

Use the arp command to show the cache of mapping MAC addresses to hostnames or IP addresses. Note that you can use arp -n to prevent hostname resolution and show IP addresses instead of DNS names.

Or, using a more modern approach with ip :

$ ip neigh 
192.168.178.34 dev wlp1s0 lladdr 00:25:4b:9b:64:49 STALE
192.168.178.1 dev wlp1s0 lladdr 3c:a6:2f:8e:66:b3 REACHABLE

1

Use the ip command to show the cache of mapping MAC addresses to IP addresses.

To display, configure, and troubleshoot wireless devices, you want to use the iw command . For example, I know that my wireless NIC is called wlp1s0 , so I can query it:

$ iw dev wlp1s0 info 
Interface wlp1s0
        ifindex 2
        wdev 0x1
        addr 38:de:ad:37:32:0f
        ssid FRITZ!Box 7530 QJ 
        type managed
        wiphy 0
        channel 5 (2432 MHz), width: 20 MHz, center1: 2432 MHz 
        txpower 20.00 dBm

1

Show base information about wireless interface wlp1s0 .

2

The router the interface is connected to (see also the next example).

3

The WiFi frequency band the interface is using.

Further, I can gather router- and traffic-related information like so:

$ iw dev wlp1s0 link 
Connected to 74:42:7f:67:ca:b5 (on wlp1s0)
        SSID: FRITZ!Box 7530 QJ
        freq: 2432
        RX: 28003606 bytes (45821 packets) 
        TX: 4993401 bytes (15605 packets)
        signal: -67 dBm
        tx bitrate: 65.0 MBit/s MCS 6 short GI

        bss flags:      short-preamble short-slot-time
        dtim period:    1
        beacon int:     100

1

Show connection information about wireless interface wlp1s0 .

2

This and the next line send ( TX stands for “transmit”) and receive ( RX ) statistics—that is, bytes and packets sent and received via this interface .

Now that we have a good handle on what’s going on in the lowest layer of the TCP/IP stack, the (data) link layer, let’s move up the stack.

The Internet Layer

The second-lowest layer of the TCP/IP stack, the internet layer, is concerned with routing packets from one machine on the network to another. The design of the internet layer assumes that the available network infrastructure is unreliable and that the participants (such as nodes in the network or the connections between them) change frequently.

The internet layer provides best-effort delivery (that is, no guarantees concerning performance) and treats every packet as independent. As a consequence, higher layers, typically the transport layer, take care of addressing reliability issues, including packet order, retries, or delivery guarantees.

How Routing Is Like Surface Mail

Think of an internet layer address as similar to your postal address. This postal address is made up of a number of parts, from the most coarse grained (the country) down to the street-level information, including house number.

That postal address is all I need to know to make sure that I can send, say, a postcard to you from anywhere in the world. Note also that I don’t need to know the details of the transportation (such as when my postcard travels via ship or plane, or what exact path is taken). The contract between me and the post office is simple: if I put the correct address on it and pay the correct amount (via the right stamp), the post office promises to deliver it.

Likewise, your machine is identified by the internet layer via a logical address.

In this layer, the dominating protocol for logically identifying machines uniquely, worldwide, is the Internet Protocol (IP), which comes in two flavors, IP version 4 (IPv4) and IP version 6 (IPv6).

IPv4

IPv4 defines unique 32-bit numbers identifying a host or process acting as an endpoint in a TCP/IP communication.

One way to write IPv4 addresses is to split up the 32-bit into four 8-bit segments separated by a period, each segment in the 0 to 255 range, called an octet (hinting at that the segment covers 8 bits). Let’s have a look at a concrete example:

 63.32.106.149
\_/\_/ \_/ \_/
 |  |   |   └─ 
 |  |   └───── 
 |  └───────── 
 └────────────

1

First octet in binary form: 00111111

2

Second octet in binary form: 00100000

3

Third octet in binary form: 01101010

4

Fourth octet in binary form: 10010101

The IP header ( Figure 7-3 ), as defined in RFC 791 and related IETF specs, has a number of fields, but the following are the most important ones that you should be aware of:

Source address (32 bits)

The IP address of the sender

Destination address (32 bits)

The IP address of the receiver

Protocol (8 bits)

The payload type (next-higher layer type), as per RFC 790 —for example, TCP, UDP, or ICMP

Time to live, aka TTL (8 bits)

The maximal time the packet is allowed to exist

Type of service (8 bits)

Can be used for quality of service (QoS) purposes

lmlx 0703

Figure 7-3. The IP header format as per RFC 791

Given that the internet is a network of networks, it seems natural to distinguish between networks and single machines (hosts) in the networks. IP address ranges are assigned to networks and within those networks to individual hosts.

Today, the Classless Inter-Domain Routing (CIDR) is the only relevant method for assigning IP addresses. The CIDR format consists of two parts:

  • The first part represents the network address. This looks like a normal IP address—for example, 10.0.0.0 .

  • The second part defines how many bits (and with that, IP addresses) fall within the address range—for example, /24 .

So, a complete CIDR range example looks like the following:

10.0.0.0/24

In the preceding example, the first 24 bits (or three octets) represent the network, and the last 8 bits (32 bits overall minus the 24 bits for the network) are the IP addresses available for the 256 hosts (2 8 ). The first IP address in this CIDR range is 10.0.0.0 , and the last IP address is 10.0.0.255 . Strictly speaking, only the addresses 10.0.0.1 to 10.0.0.254 can be assigned to hosts since the .0 and .255 addresses are reserved for special purposes. In addition, we can say that the netmask is 255.255.255.0 since that’s the first 24 bits representing the network.

In practice, you don’t need to remember all the math here. If you’re dealing with CIDR ranges on a daily basis, then you just know, and if you’re a casual user, you may want to use some tooling. If you want to do CIDR range calculations, such as determining how many IPs are in a range, the following are available:

There are also some notable reserved IPv4 addresses you should know:

127.0.0.0

This subnet is reserved for local addresses, with the most prominent one being the loopback address 127.0.0.1 .

169.254.0.0/16 ( 169.254.0.0 to 169.254.255.255 )

These are link local addresses, meaning packets sent there should not be forwarded to other parts of the network. Some cloud providers such as Amazon Web Services use this for special services (metadata).

224.0.0.0/24 ( 224.0.0.0 to 239.255.255.255 )

This range is reserved for multicast.

RFC 1918 defines private IP ranges. A private IP range means that the IP addresses in it are not routable on the public internet; hence, it is safe to assign them internally (for example, in the context of your company):

  • 10.0.0.0 to 10.255.255.255 (the 10/8 prefix)

  • 172.16.0.0 to 172.31.255.255 ( 172.16/12 prefix)

  • 192.168.0.0 to 192.168.255.255 ( 192.168/16 prefix)

Another interesting IPv4 address is 0.0.0.0 . It is a nonroutable address that has different use cases and different meanings depending on the context, but the most important one, from a server perspective, is that 0.0.0.0 refers to all IPv4 addresses present in the machine. That’s a great way to say “listen on all available IP addresses” as a source until it turns into a known IP.

That was a lot of dry theory; let’s see it in action. We’ll start by querying the machine for IP-related things (output edited):

$ ip addr show 
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue
    state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo 
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: wlp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
    noqueue state UP group default qlen 1000
    link/ether 38:de:ad:37:32:0f brd ff:ff:ff:ff:ff:ff
    inet 192.168.178.40/24 brd 192.168.178.255 scope global dynamic 
    noprefixroute wlp1s0
       valid_lft 863625sec preferred_lft 863625sec
    inet6 fe80::be87:e600:7de7:e08f/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

1

List addresses of all interfaces.

2

The IP address of the loopback interface ( 127.0.0.1 , as expected).

3

The (private) IP address of the wireless NIC. Note that this is the LAN-local IP address of the machine, which isn’t publicly routable since it falls in the 192.168/16 range.

The IPv4 address space is already exhausted, and given that there are many more endpoints today than the internet designers thought there would be (for example, due to mobile devices and IoT), a sustainable solution is needed.

Luckily, with IPv6 there is a solution for the address-exhaustion issue. Unfortunately, at this time of writing, the ecosystem at large has still not made the move to IPv6, partly for infrastructure reasons but also due to a lack of tooling that supports IPv6. This means that for the time being you’ll still have to deal with IPv4 and its limitations and workarounds .

Let’s have a look at the (hopefully not-too-distant) future: IPv6.

IPv6

Internet Protocol version 6 (IPv6) is a 128-bit number identifying an endpoint in a TCP/IP communication. This means that with IPv6 we can assign on the order of 10 38 individual machines (devices). In contrast to IPv4, IPv6 uses a hexadecimal representation, eight groups of 16 bits each, separating the groups by a colon ( : ).

There are a few rules for shortening IPv6 addresses, such as removing leading zeros or compressing consecutive sections of zeros by replacing them with two colons ( :: ). For example, the IPv6 loopback address can be written abbreviated as ::1 (the IPv4 variant would be 127.0.0.1 ).

Just like IPv4, IPv6 has a number of special and reserved addresses; see APNIC’s listing of IPv6 address types for examples.

It’s important to note that IPv4 and IPv6 are not compatible. This means that IPv6 support needs to be built into each and every network participant, from edge devices (like your phone) to routers to server software. This IPv6 support has, at least in the context of Linux, already shown to be pretty wide. For example, the ip addr command we saw in the section “IPv4” would already by default show us the IPv6 addresses.

Internet Control Message Protocol

The RFC 792 defines the Internet Control Message Protocol (ICMP), which is used for lower-level components to send error messages and operational information like availability.

Let’s see ICMP in action by testing the reachability of a website with ping :

$ ping mhausenblas.info
PING mhausenblas.info (185.199.109.153): 56 data bytes
64 bytes from 185.199.109.153: icmp_seq=0 ttl=38 time=23.140 ms
64 bytes from 185.199.109.153: icmp_seq=1 ttl=38 time=23.237 ms
64 bytes from 185.199.109.153: icmp_seq=2 ttl=38 time=23.989 ms
64 bytes from 185.199.109.153: icmp_seq=3 ttl=38 time=24.028 ms
64 bytes from 185.199.109.153: icmp_seq=4 ttl=38 time=24.826 ms
64 bytes from 185.199.109.153: icmp_seq=5 ttl=38 time=23.579 ms
64 bytes from 185.199.109.153: icmp_seq=6 ttl=38 time=22.984 ms
^C
--- mhausenblas.info ping statistics ---
7 packets transmitted, 7 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 22.984/23.683/24.826/0.599 ms

Alternatively, you can use gping , which can ping multiple targets at the same time and plot a graph on the command line (see Figure 7-4 ).

lmlx 0704

Figure 7-4. Pinging two websites with gping

Note that an equivalent tool is available for IPv6: the aptly named ping6 .

Routing

Part of the network stack in Linux is concerned with routing—that is, deciding on a per-packet basis where to send a packet. The destination could be a process on the same machine, or it could be an IP address on a different machine.

While the exact implementation details of routing are beyond the scope of this chapter, we’ll provide a high-level overview: iptables , a widely used tool that allows you to manipulate the routing tables—for example, to reroute packets on certain conditions or implement a firewall—uses netfilter to intercept and manipulate packets.

What you should know is how to query and display routing information, as follows:

$ sudo route -n 
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.178.1   0.0.0.0         UG    600    0        0 wlp1s0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlp1s0
192.168.178.0   0.0.0.0         255.255.255.0   U     600    0        0 wlp1s0

1

Use the route command with -n , forcing numerical IP addresses.

The detailed meaning of the tabular output in the previous route command is as follows:

Destination

The IP address of the destination; 0.0.0.0 means it’s unspecified or unknown, potentially sending it to the gateway.

Gateway

For packets not on the same network, the gateway address.

Genmask

The subnet mask used.

Flags

UG means the network is up and is a gateway.

Iface

The network interface the packet is going to use.

A modern way is using ip like so:

$ sudo ip route
default via 192.168.178.1 dev wlp1s0 proto dhcp metric 600
169.254.0.0/16 dev wlp1s0 scope link metric 1000
192.168.178.0/24 dev wlp1s0 proto kernel scope link src 192.168.178.40 metric 600

Is it down? We can check connectivity as follows:

$ traceroute mhausenblas.info
traceroute to mhausenblas.info (185.199.108.153), 30 hops max, 60 byte packets
 1  _gateway (192.168.5.2)  1.350 ms  1.306 ms  1.293 ms

Note that we will discuss a number of TCP/IP-related troubleshooting and performance tools in “Monitoring” .

To round things off, I’ll also briefly mention the Border Gateway Protocol (BGP) as defined in RFC 4271 and other IETF specs. While it’s unlikely that you’ll interact directly with BGP (unless you work at a network provider or admin a network), it’s crucial to be aware of its existence and understand at a high level what it does.

Facebook Disappears from the Internet

In late 2021, we saw the impact that BGP misconfiguration can have. Read the backstory and lessons learned in “Understanding How Facebook Disappeared from the Internet” .

We said earlier on that the internet really is a network of networks. In BGP terminology, a network is called an autonomous system (AS). For IP routing to work, these ASs need to share their routing and reachability data, announcing routes to deliver packets across the internet .

Now that you know the fundamental workings of the internet layer—how addresses and routing work—let’s move up the stack.

The Transport Layer

In this layer, it’s all about the nature of the communication between endpoints. There are connection-oriented protocols and connection-less ones. Reliability, QoS, and in-order delivery may be a concern.

Note

There are attempts in modern protocol design— HTTP/3 is an example—to combine functionality, such as moving parts of TCP into higher-level protocols.

Ports

One core concept in this layer is that of ports. No matter which protocol is used in this layer, each requires ports. A port is a unique 16-bit number identifying a service available at an IP address. Think of it this way: a single (virtual) machine may have a number of services (see “Application Layer Networking” ) running, and you need to be able to identify each in the context of the machine’s IP.

We differentiate between the following:

Well-known ports (from 0 to 1023)

These are for daemons such as an SSH server or a web server. Using (binding to) one of them requires elevated privileges ( root or CAP_NET_BIND_SERVICE capability, as discussed in “Capabilities” ).

Registered ports (from 1024 to 49151)

These are managed by Internet Assigned Numbers Authority (IANA) through a publicly documented process.

Ephemeral ports (from 49152 to 65535)

These cannot be registered. They can be used for automatically allocating a temporary port (for example, if your app connects to a web server, it needs a port itself, as the other endpoint of the communication) as well as for private (say, company-internal) services.

You can see the ports and mapping in /etc/services , and further, there is a comprehensive list of TCP and UDP port numbers you might want to consult if you’re unsure.

If you want to see what’s in use on your local machine ( do not do this on someone else’s machine/against a nonlocal IP):

$ nmap -A localhost 

Starting Nmap 7.60 ( https://nmap.org ) at 2021-09-19 14:53 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00025s latency).
Not shown: 999 closed ports
PORT    STATE SERVICE VERSION
631/tcp open  ipp     CUPS 2.2 
| http-methods:
|_  Potentially risky methods: PUT
| http-robots.txt: 1 disallowed entry
|_/
|_http-server-header: CUPS/2.2 IPP/2.1
|_http-title: Home - CUPS 2.2.7

Service detection performed. Please report any incorrect results
at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 6.93 seconds

1

Scan ports on local machine.

2

Found one open port, 631, which is the Internet Printing Protocol (IPP).

With the general idea of ports explained, let’s now have a look how these ports are used in different transport layer protocols.

Transmission Control Protocol

The Transmission Control Protocol (TCP) is a connection-oriented transport layer protocol that is used by a number of higher-level protocols, including HTTP and SSH (see “Application Layer Networking” ). It is a session-based protocol that guarantees delivery of the packets in order and supports retransmission in case of errors.

The TCP header ( Figure 7-5 ), as defined in RFC 793 and related IETF specs, has these most important fields:

Source port (16 bits)

The port used by the sender.

Destination port (16 bits)

The port used by the receiver.

Sequence number (32 bits)

Used to manage in-order delivery.

Acknowledgment number (32 bits)

This number and the SYN and ACK flags are the core of the so-called TCP/IP three-way handshake .

Flags (9 bits)

Most important, the SYN (synchronize) and the ACK (acknowledgement) bits.

Window (16 bits)

The receive window size.

Checksum (16 bits)

A checksum of the TCP-header, used for error checking.

Data

The payload to transport.

lmlx 0705

Figure 7-5. The TCP header format as per RFC 793

TCP tracks the state of the connection from establishment to termination, with both the sender and the receiver having to negotiate certain things, from how much data to send (TCP window size) to QoS.

From a security perspective, TCP is without any defense mechanisms. In other words, the payload is sent in plain text, and anyone between the sender and the receiver (and there are by design many hops) can inspect the packet; see “Wireshark and tshark” for details on using Wireshark and tshark to inspect the payload. To enable encryption of the message, you need to use the Transport Layer Security (TLS) protocol, ideally in version 1.3 as per RFC 8446 .

With that, let’s move on to the most important stateless transport layer protocol: UDP.

User Datagram Protocol

User Datagram Protocol (UDP) is a connection-less transport layer protocol allowing you to send messages, called datagrams in UDP, without communication setups (such as TCP does with the handshake). It does, however, support datagram checksums to ensure integrity. There are a number of application-level protocols, such as NTP and DHCP (see “Application Layer Networking” ) as well as DNS (see “DNS” ), that use UDP.

The RFC 768 defines the UDP header format as shown in Figure 7-6 . Its most important fields are the following:

Source port (16 bits)

The port used by the sender; optional, and if not, use 0

Destination port (16 bits)

The port used by the receiver

Length (16 bits)

The total length of the UDP header and data

Checksum (16 bits)

Can optionally be used for error checking

Data

The payload of the datagram

lmlx 0706

Figure 7-6. The UDP header format as per RFC 768

UDP is a very simple protocol and requires the higher-level protocol that works on top of it to take care of many of the things that TCP would handle itself. On the other hand, UDP has very little overhead and can achieve high throughput. It’s very simple to use; see also the UDP manual page .

Sockets

A high-level communication interface that Linux provides are sockets . Think of them as endpoints in a communication, with their distinct identity: a tuple made up of the TCP or UDP port and the IP address.

It’s likely that you’ll only use sockets if you want to develop network-related tooling or apps, but you should at least be aware of how to query them. For example, in the context of the Docker daemon , you at least need to know about the required permissions for the socket.

Let’s have a look at how to use the ss command to display socket-related information.

Let’s assume we want to get an overview of the TCP sockets in use on the system:

$ ss -s 
Total: 913 (kernel 0)
TCP:   10 (estab 4, closed 1, orphaned 0, synrecv 0, timewait 1/0), ports 0 

Transport Total     IP        IPv6 
*         0         -         -
RAW       1         0         1
UDP       10        8         2
TCP       9         8         1
INET      20        16        4
FRAG      0         0         0

1

Use the ss command to query ports (with -s , we ask for a summary).

2

The summary for TCP; overall, 10 sockets in use.

3

A more detailed overview, breaking down by type and IP version.

Now, what about UDP? Can we get this information, maybe with some more details, such as endpoint IP addresses? Turns out this is also possible with ss (output edited):

$ ss -ulp 
State    Recv-Q  Send-Q   Local Address:Port     Peer Address:Port
UNCONN   0       0              0.0.0.0:60360         0.0.0.0:*
UNCONN   0       0        127.0.0.53%lo:domain        0.0.0.0:*
UNCONN   0       0              0.0.0.0:bootpc        0.0.0.0:*
UNCONN   0       0              0.0.0.0:ipp           0.0.0.0:*
UNCONN   0       0              0.0.0.0:mdns          0.0.0.0:*
UNCONN   0       0                 [::]:mdns             [::]:*
UNCONN   0       0                 [::]:38359            [::]:*

1

Use ss : the -u parameter restricts to UDP sockets, -l is for selecting listening sockets, and -p also shows the process information (none in our case).

Another tool you might find handy in this context (sockets and processes) is lsof . For example, let’s see what UDP sockets Chrome uses on my machine (output edited):

 $ lsof -c chrome -i udp | head -5 
COMMAND   PID USER   FD  TYPE   DEVICE     NODE NAME
chrome   3131  mh9  cwd   DIR      0,5   265463 /proc/5321/fdinfo
chrome   3131  mh9  rtd   DIR      0,5   265463 /proc/5321/fdinfo
chrome   3131  mh9  txt   REG    253,0  3673554 /opt/google/chrome/chrome
chrome   3131  mh9  mem   REG    253,0  3673563 /opt/google/chrome/icudtl.dat
chrome   3131  mh9  mem   REG    253,0 12986737 /usr/lib/locale/locale-archive

1

Use lsof with -c to specifically select a process by name as well as limit to UDP with -i . Note that the overall output would be many dozens of lines; that’s why I cut it down to five with the head -5 command in the pipe.

With that we’ve covered the three lower layers of the TCP/IP stack. Since the application layer has so much going on, I’ve dedicated two sections to it: first, we’re looking into the global-scale naming system, and then we’ll look into a number of application layer (or layer 7) protocols and applications, such as the web.

DNS

We learned that the internet layer of the TCP/IP stack defines so-called IP addresses whose main function it is to identify machines, virtual or physical alike. In the context of “Containers” , we go so far as to assign IP addresses to individual containers. There are two challenges with numerical IP addresses, no matter if IPv4 or IPv6:

  • As humans, we generally remember names better than we do (long) numbers. For example, if you want to share a website with a friend, you can just say it’s ietf.org they should check out rather than 4.31.198.44 .

  • Due to the way the internet and its applications are built, IP addresses often change. You might get a new server with a new IP address in a more traditional setup. Or, in the context of containers, you may be rescheduled onto a different host, in which case the container automatically gets a new IP address assigned.

So, in a nutshell, IP addresses are hard to remember and can change, while a name (for a server or a service) remains the same. This challenge has existed since the beginning of the internet and since UNIX supported the TCP/IP stack.

The way to address this was to locally (in the context of a single machine) maintain a mapping between names and IP addresses via /etc/hosts . The Network Information Center (NIC) would share a single file called HOSTS.TXT via FTP with all participating hosts.

Very soon it became clear that this centralized approach could not keep up with the growing internet, and in the early 1980s, a distributed system was designed. Paul Mockapetris was the lead architect.

The DNS is a worldwide, hierarchical naming system for hosts and services on the internet. While there are many related RFCs, the original one, RFC 1034 , and its implementation guidance via RFC 1035 are still valid, and I strongly recommend you read them if you want to learn more about the motivation and design.

The DNS uses a number of terms, but the following are the main concepts:

Domain name space

A tree structure with . as the root and each tree node and leaf containing information about a certain space. The labels (63 bytes maximum length) along the path from a leaf to the root is what we call a fully qualified domain name (FQDN). For example, demo.mhausenblas.info. is an FQDN with the so-called top-level domain .info . Note that the right-most dot, the root, is often left off.

Resource records

The payload in the nodes or leaves of the domain name space (see “DNS Records” ).

Name servers

Server programs that hold information about the domain tree’s structure. If a name server has the complete information about a space, it’s called an authoritative name server . Authoritative information is organized into zones.

Resolvers

Programs that extract information from name servers in response to client requests. They are machine local, and no explicit protocol is defined for the interaction between a resolver and a client. Often there are library calls supported for resolving the DNS.

Figure 7-7 shows a complete setup of a DNS system, including user program, resolver, and name server(s), as described in RFC 1035. In the query process, the resolver would iteratively query authoritative name servers (NS) starting from the root or, if supported, using a recursive query where an NS queries others on behalf of a resolver.

lmlx 0707

Figure 7-7. A complete DNS example setup
Note

Although they’re still around, we usually don’t use the DNS resolver configuration in /etc/resolv.conf in modern systems, especially when DHCP (see “Dynamic Host Configuration Protocol” ) is deployed.

The DNS is a hierarchical naming system, and at its root sit 13 root servers that manage the records for the top-level domains. Directly beneath the root are the top-level domains (TLD) :

Infrastructure top-level domain

Managed by IANA on behalf of the IETF and including, for example, example and localhost

Generic top-level domains (gTLD)

Generic domains having three or more characters, such as .org or .com

Country-code top-level domains (ccTLD)

For countries or territories assigned two-letter ISO country codes

Sponsored top-level domains (sTLD)

For private agencies or organizations that establish and enforce rules restricting the eligibility to use the TLD—for example, .aero and .gov

Let’s have a closer look at some moving parts of the DNS and how to use it in practice.

DNS Records

A name server manages records that capture the type, the payload, and other fields, including things like the time to live (TTL), the time period after which the record is supposed to be discarded. You can think of the FQDN as the address of the node and the resource record (RR) as the payload, the data in the node.

DNS has a number of record types , including the following most important ones (in alphabetical order):

A records (RFC 1035) and AAAA records (RFC 3596)

IPv4 and IPv6 address records, respectively; usually used to map hostnames to an IP address of the host.

CNAME records (RFC 1035)

Canonical name records providing an alias of one name to another.

NS records (RFC 1035)

Name server records delegating a DNS zone to use the authoritative name servers.

PTR records (RFC 1035)

Pointer records used for performing reverse DNS lookups; the opposite of A records.

SRV records (RFC 2782)

Service locator records. They are a generalized discovery mechanism, rather than hardcoded (as traditionally was the case with the MX record type for mail exchange).

TXT records (RFC 1035)

Text records. These were originally meant for arbitrary human-readable text but over time found a new use case. Today, these records often have machine-readable data in the context of security-related DNS extensions.

There are also wildcard records starting with the asterisk label ( * )—for example, *.mhausenblas.info —as a catch-all to match requests for nonexistent names.

Let’s see how these records look in practice. The DNS records are represented in a textual form in a zone file that a name server—such as bind —reads in and makes part of its database:

$ORIGIN example.com. 
$TTL 3600 
@   SOA nse.example.com. nsmaster.example.com. (
        1234567890 ; serial number
        21600      ; refresh after 6 hours
        3600       ; retry after 1 hour
        604800     ; expire after 1 week
        3600 )     ; minimum TTL of 1 hour
example.com.  IN  NS    nse 
example.com.  IN  MX    10 mail.example.com. 
example.com.  IN  A     1.2.3.4 
nse           IN  A     5.6.7.8 
www           IN  CNAME example.com. 
mail          IN  A     9.0.0.9

1

The start of this zone file in the namespace.

2

Default expiration time in seconds of all RRs that don’t define their own TTL.

3

The nameserver for this domain.

4

The mailserver for this domain.

5

The IPv4 address for this domain.

6

The IPv4 address for the nameserver.

7

Make www.example.com an alias for this domain—that is, example.com .

8

The IPv4 address for the mail server.

Putting all the concepts discussed together, we can now understand the example shown in Figure 7-8 . This shows a part of the global domain name space and a concrete example FQDN, demo.mhausenblas.info :

.info

A generic TLD managed by a company called Afilias .

mhausenblas.info

A domain I bought. Within this zone I can assign subdomains as I please.

demo.mhausenblas.info

The subdomain I assigned for demo purposes.

lmlx 0708

Figure 7-8. The domain name space and an example path (FQDN)

Consider how in the previous example each entity (Afilias or me) only looks after its part, and no coordination is required. For example, to create the demo subdomain, I only had to change my DNS settings for the zone, without asking anyone at Afilias for support or permissions. This seemingly simple fact is the core of the decentralized nature of DNS and is what makes it so scalable.

Now that we know how the domain name space is structured and the information in the nodes is represented, let’s see how you can query them.

DNS Lookups

With all the infrastructure in place, mainly nameservers and resolvers, we now look at performing DNS queries. There is a lot of logic in the evaluation and construction of the resolution (mostly covered in RFC 1034 and 1035), but this is beyond the scope of the book. Let’s have a look at how you can do the query without having to understand the internals.

You can use the host command to query local (and global) names to resolve them to IP addresses and the other way around:

$ host -a localhost 
Trying "localhost.fritz.box"
Trying "localhost"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49150
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;localhost.                     IN      ANY

;; ANSWER SECTION:
localhost.              0       IN      A       127.0.0.1
localhost.              0       IN      AAAA    ::1

Received 71 bytes from 127.0.0.53#53 in 0 ms

$ host mhausenblas.info 
mhausenblas.info has address 185.199.110.153
mhausenblas.info has address 185.199.109.153
mhausenblas.info has address 185.199.111.153
mhausenblas.info has address 185.199.108.153

$ host 185.199.110.153 
153.110.199.185.in-addr.arpa domain name pointer cdn-185-199-110-153.github.com.

1

Look up local IP addresses.

2

Look up FQDN.

3

Reverse lookup of IP address to find an FQDN; looks like the GitHub CDN.

A more powerful way to look up the DNS records is using the dig command:

$ dig mhausenblas.info 
; <<>> DiG 9.10.6 <<>> mhausenblas.info
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43159
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 2, ADDITIONAL: 5

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;mhausenblas.info.              IN      A

;; ANSWER SECTION: 
mhausenblas.info.       1799    IN      A       185.199.111.153
mhausenblas.info.       1799    IN      A       185.199.108.153
mhausenblas.info.       1799    IN      A       185.199.109.153
mhausenblas.info.       1799    IN      A       185.199.110.153

;; AUTHORITY SECTION: 
mhausenblas.info.       1800    IN      NS      dns1.registrar-servers.com.
mhausenblas.info.       1800    IN      NS      dns2.registrar-servers.com.

;; ADDITIONAL SECTION:
dns1.registrar-servers.com. 47950 IN    A       156.154.132.200
dns2.registrar-servers.com. 47950 IN    A       156.154.133.200
dns1.registrar-servers.com. 28066 IN    AAAA    2610:a1:1024::200
dns2.registrar-servers.com. 28066 IN    AAAA    2610:a1:1025::200

;; Query time: 58 msec
;; SERVER: 172.16.173.64#53(172.16.173.64)
;; WHEN: Wed Sep 15 19:22:26 IST 2021
;; MSG SIZE  rcvd: 256

1

Using dig , look up the DNS records of the FQDN mhausenblas.info .

2

The DNS A records.

3

The authoritative nameserver.

There are alternatives to the dig command available, notably dog and nslookup ; see Appendix B .

Tip

One saying you will come across often is: “It’s always DNS.” But what does this mean? It’s about troubleshooting and understanding that DNS is a distributed database with many moving parts. When debugging DNS-related issues, consider the TTL of records and that there are many caches, from local ones in your app to resolver, to anything between you and the nameservers.

In “DNS Records” , we mentioned the SRV record type and that it serves as a generic discovery mechanism. So, rather than defining a new record type for a new service in an RFC, the community came up with a generic way to address any upcoming service type. This mechanism, described in RFC 2782 , explains how SRV records can be used to communicate the IP address and port of a service via DNS.

Let’s see that in practice. Say we want to know what chat services—more specifically, Extensible Messaging and Presence Protocol (XMPP) services—if any, are available:

$ dig +short _xmpp-client._tcp.gmail.com. SRV 
20 0 5222 alt3.xmpp.l.google.com.
5 0 5222 xmpp.l.google.com. 
20 0 5222 alt4.xmpp.l.google.com.
20 0 5222 alt2.xmpp.l.google.com.
20 0 5222 alt1.xmpp.l.google.com.

1

Use the dig command with the +short option to display only the relevant answer section. The _xmpp-client._tcp part is the format RFC 2782 prescribes, and the SRV at the end of this command specifies what record type we’re interested in.

2

Overall there are five answers. An example service instance is available at xmpp.l.google.com:5222 with a TTL of 5 seconds. If you have an XMPP such as Jabber, you could use this address for configuration input.

With this, we’ve reached the end of the DNS section . Now we’ll have a look at other application layer protocols and tooling.

Application Layer Networking

In this section, we focus on user space or application layer network protocols, tooling, and apps. As an end user, you’ll likely spend most of your time here, using things such as web browsers or mail clients for your daily tasks.

The Web

The web, originally developed by Sir Tim Berners-Lee in the early 1990s, has three core components:

Uniform Resource Locators (URL)

As per RFC 1738 originally and a number of updates and related RFCs. A URL defines both the identity and the location of a resource on the web. A resource could be a static page or a process that generates content dynamically.

Hypertext Transfer Protocol (HTTP)

HTTP defines an application layer protocol and how to interact with content available via URLs. As per RFC 2616 for v1.1, but there are also more modern versions, such as HTTP/2, defined in RFC 7540 , and the HTTP/3 draft (which at the time of this writing was still in the works). Core HTTP concepts are:

HTTP methods

Including GET for read operations and, among others, POST for write operations, these define a CRUD-like interface.

Resource naming

This dictates how to form URLs.

HTTP status codes

With the 2xx range for success, 3xx for redirects, 4xx for client errors, and 5xx for server errors.

Hyper Text Markup Language (HTML)

Initially a W3C specification, HTML is now a living standard available via WHATWG . A hypertext markup allows you to define page elements such as headers or inputs.

W3C and standards

Technically neither IETF nor W3C (World Wide Web Consortium) do standards. They create specifications through formal processes that the community accepts as de facto standards. I strongly recommend that you read these specifications and try to understand what’s going in there. For me, in 2006, after using and building web sites and applications for almost a decade, I started to take this seriously (when I got involved in W3C efforts), and the payoff was enormous.

Let’s have a closer look at how URIs (the generic version of URLs) are constructed (as per RFC 3986) and how that maps to HTTP URLs:

michaelh:12345678@http://example.com:4242/this/is/the/way?orisit=really#another
\______/ \______/ \__/   \_____________/\______________/ \___________/ \_____/
   |        |       |          |                |              |          |
   v        v       v          v                v              v          v
user password  scheme  authority             path          query   fragment

The components are as follows:

user and password (both optional)

Initially used for basic authentication, these components should not be used anymore. Instead, for HTTP, you should be using a proper authentication mechanism together with HTTPS for encryption on the wire.

scheme

Refers to the URL scheme , an IETF specification defining its meaning. For HTTP, that scheme is called http , which really is a family of HTTP specifications, such as RFC 2616.

authority

The hierarchical naming part. For HTTP, this is:

Hostname

Either as a DNS FQDN or an IP address.

Port

With a default of 80 (so example.com:80 and example.com are the same).

path

A scheme-specific part for further resource details.

query and fragment (both optional)

The former appears after the ? for nonhierarchical data (for example, to express tags or form data), and the latter appears after the # for secondary resources (in the context of HTML, that could be a section).

Today, the web has advanced far beyond its humble 1990s roots, with a number of technologies such as JavaScript/ECMAScript and Cascading Style Sheets (CSS) considered core. Those additions, JavaScript for dynamic client-side content and CSS for styling, have eventually led to single-page web apps . While this topic is beyond the scope of the book, it’s important to remember that knowing the basics (URL, HTTP, and HTML) well goes a long way in terms of understanding how things work and troubleshooting issues you may have.

Let’s now see web specifications in action by simulating the flow end to end, starting at the HTTP server end.

You can rather easily run a simple HTTP server that only serves the content of a directory in two ways: by using Python or by using netcat ( nc ) .

With Python, to serve the content of a directory, you would do the following:

$ python3 -m http.server 
Serving HTTP on :: port 8000 (http://[::]:8000/) ... 
::ffff:127.0.0.1 - - [21/Sep/2021 08:53:53] "GET / HTTP/1.1" 200 -

1

Use the built-in Python module http.server to serve the content of the current directory (that is, the directory from which you launched this command).

2

It confirms that it’s ready to serve via port 8000. This means that you could enter [_http://localhost:8000](http://localhost:8000)_ into your browser and you would see the content of your directory there.

3

This shows that an HTTP request against the root ( / ) has been issued and served successfully (the 200 HTTP response code).

Tip

If you want to do more advanced stuff, beyond serving a static directory, consider using a proper web server such as NGINX . You could, for example, run NGINX using Docker (see “Docker” ) with the following command:

$ docker run --name mywebserver \ 
             --rm -d \ 
             –v  "$PWD":/usr/share/nginx/html:ro \ 
             -p 8042:80 \ 
             nginx:1.21

1

Call the running container mywebserver ; you should see that when you issue a docker ps command to list running containers.

2

The --rm removes the container on exit, and the -d turns it into a daemon (detach from terminal, run in background).

3

Mounts the current directory ( $PWD ) into the container as the NGINX source content directory. Note that $PWD is a bash way to address the current directory. In Fish you would use (pwd) instead.

4

Makes the container-internal port 80 available on the host via 8042. That means you would be able to access the web server via [_http://localhost:8042](http://localhost:8042)_ on your machine.

5

The container image to use ( nginx:1.21 ), and implicitly using Docker Hub since we didn’t specify the registry part.

Now let’s see how we can use curl , a powerful and popular tool to interact with any kind of URLs, to get the content of the web server we launched in the previous example (make sure it’s still running, or launch it again in a separate session if you terminated it already):

$ curl localhost:8000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                      "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
<li><a href="app.yaml">app.yaml</a></li>
<li><a href="Dockerfile">Dockerfile</a></li>
<li><a href="example.json">example.json</a></li>
<li><a href="gh-user-info.sh">gh-user-info.sh</a></li>
<li><a href="main.go">main.go</a></li>
<li><a href="script.sh">script.sh</a></li>
<li><a href="test">test</a></li>
</ul>
<hr>
</body>

In Table 7-1 you see some common options for curl that you may find useful. The selection is based on my usage history for a range of tasks, from developing to system administration.

Table 7-1. Useful options for curl | Option | Long-form option | Description and use case | | --- | --- | --- | | -v | --verbose | For verbose output, use for debugging. | | -s | --silent | Silence curl : do not show the progress meter or error messages. | | -L | --location | Follow page redirects ( 3XX HTTP response codes). | | -o | --output | By default, the content goes to stdout ; if you want to directly store it in a file, specify it via this option. | | -m | --max-time | Maximum time (in seconds) you are willing to wait for the operation to take. | | -I | --head | Fetch the headers only (careful: not every HTTP server supports the HEAD method for a path). | | -k | --insecure | By default, HTTPS calls are verified. Use this option to ignore the errors for cases where that’s not possible. |

If curl is not available, you can fall back to wget , which is more limited but sufficient for simple HTTP-related interactions.

Secure Shell

Secure Shell (SSH) is a cryptographic network protocol for securely offering network services on an unsecured network. For example, as a replacement for telnet , you can use ssh to log into a remote machine and also move data securely between (virtual) machines.

Let’s see SSH in action. I’ve provisioned a virtual machine in the cloud with an IP address of 63.32.106.149 , and the user name provided by default is ec2-user . To log into the machine, I can do the following (note that the output is edited and assumes that you or someone else created credentials in ~/.ssh/lml.pem beforehand):

$ ssh \ 
    -i ~/.ssh/lml.pem \ 
    [email protected] 

...

https://aws.amazon.com/amazon-linux-2/
11 package(s) needed for security, out of 35 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-26-8-138 ~]$

1

Use the ssh command to log into a remote machine.

2

Use the identity file ~/.ssh/lml.pem rather than a password. Explicitly providing that file is a good practice but in our case would strictly speaking not be necessary as it resides in the default location ~/.ssh .

3

The SSH target machine in the format username@host .

4

Once the login process is completed, I can tell from the prompt that I’m on the target machine and can use it just as if it were local.

Some general SSH usage tips:

  • If you run an SSH server, that is, allow others to ssh into your machine, then you absolutely should disable password authentication . This forces users to create a key pair and share the public key with you that you then add to ~/.ssh/authorized_keys and allow to log in via this mechanism.

  • Use ssh -tt to force pseudo-tty allocation.

  • Do export TERM=xterm when you ssh into a machine, in case you are having display issues.

  • Configure timeouts for ssh sessions in your client. On a per-user basis, this is usually via ~/.ssh/config , where you can set ServerAliveInterval and Server​Ali⁠veCountMax options to keep your connections alive.

  • If you’re having issues, and you’ve excluded local permission issues with the key(s), then you can try launching ssh with the -v option, giving you details about what’s going on under the hood (also, try multiple instances of v , like -vvv for finer-grained debug info).

SSH is not only used directly by humans, but it is also used as a building block under the hood—for example, in file-transfer tooling.

File Transfer

One very common task involving the network is transferring files. You can do this from your local machine to a server in the cloud or from another machine in the local network.

To copy to and from remote systems, you can use one basic tool. scp (short for “secure copy”) works on top of SSH. Given that scp defaults to ssh , we need to make sure that we have the password (or even better, key-based authentication) in place for it to work.

Let’s assume we have a remote machine with the IPv4 address 63.32.106.149 , and we want to copy a file there from our local machine:

$ scp copyme \ 
      [email protected]:/home/ec2-user/ 
copyme                       100%    0     0.0KB/s   00:00

1

Source is the file copyme in the current directory.

2

Destination is the /home/ec2-user/ directory on machine 63.32.106.149 .

Synchronizing files with rsync is much more convenient and faster than scp . Under the hood, rsync uses SSH by default.

Let’s now see how we can use rsync to transfer files from the ~/data/ from the local machine to the host at 63.32.106.149 :

$ rsync -avz \ 
        ~/data/ \ 
        mh9@:63.32.106.149: 
building file list ... done
./
example.txt

sent 155 bytes  received 48 bytes  135.33 bytes/sec
total size is 10  speedup is 0.05

$ ssh [email protected] -- ls 
example.txt

1

Options meaning -a for archive (incremental, preserve), -v for verbose so that we see something, and -z for using compression.

2

Source directories (since -a includes -r which is recursive).

3

Destination in user@host format.

4

Verify if the data has arrived by executing an ls on the remote machine. The next line shows that it indeed worked—the data arrived in good order.

If you’re unsure what rsync will do, use the --dry-run option in addition to the other ones. It will essentially tell you what it will do without actually carrying out the operation, so it’s safe.

rsync is also a great tool to perform directory backups because it can be set to copy only files that have been added or changed.

Warning

Don’t forget the : after the host! Without it, rsync will happily go ahead and interpret the source or destination as a local directory. That is, the command will work fine, but rather than copying the files to the remote machine, it will end up on your local machine. For example, [email protected] as the destination would be a subdirectory of the current directory called [email protected]/ .

Last but not least, one use case you often come across is when someone provides files in an Amazon S3 bucket. To download those files, you can use the AWS CLI with the s3 subcommand as follows. We’re using a dataset from the Open Data registry in a public S3 bucket (output edited to fit):

$ aws s3 sync \ 
      s3://commoncrawl/contrib/c4corpus/CC-MAIN-2016-07/ \ 
      .\ 
      --no-sign-request 
download: s3://commoncrawl/contrib/c4corpus/CC-MAIN-2016-07/
Lic_by-nc-nd_Lang_af_NoBoilerplate_true_MinHtml_true-r-00009.seg-00000.warc.gz to
./Lic_by-nc-nd_Lang_af_NoBoilerplate_true_MinHtml_true-r-00009.seg-00000.warc.gz
download: s3://commoncrawl/contrib/c4corpus/CC-MAIN-2016-07/
Lic_by-nc-nd_Lang_bn_NoBoilerplate_true_MinHtml_true-r-00017.seg-00000.warc.gz to
./Lic_by-nc-nd_Lang_bn_NoBoilerplate_true_MinHtml_true-r-00017.seg-00000.warc.gz
download: s3://commoncrawl/contrib/c4corpus/CC-MAIN-2016-07/
Lic_by-nc-nd_Lang_da_NoBoilerplate_true_MinHtml_true-r-00004.seg-00000.warc.gz to
./Lic_by-nc-nd_Lang_da_NoBoilerplate_true_MinHtml_true-r-00004.seg-00000.warc.gz
...

1

Use the AWS S3 command to synchronize files from a public bucket.

2

This is the source bucket, s3://commoncrawl , and the exact path of the source we want to sync. Warning: there are more than 8 GB of data in that directory, so try this only if you don’t mind the bandwidth.

3

The destination is the current directory, signaled by a single period ( . ).

4

Ignore/skip authentication since this is a publicly available bucket (and thus the data in it).

The File Transfer Protocol (FTP) as per RFC 959 is still in use, but we don’t recommend using it anymore. Not only are these insecure, but there are also many better alternatives, such as the ones we discussed in this section. So, there’s no actual need for FTP anymore.

Network File System

A widely supported and used way to share files from a central location over the network is via network file system (NFS), originally developed by Sun Microsystems in the early 1980s. It saw multiple iterations as per RFC 7530 and other related IETF specs and is very stable.

You would usually have an NFS server maintained by a cloud provider or central IT in a professional setup. All you would need to do is install the client (usually through a package called nfs-common ). Then, you can mount a source directory from the NFS server as follows:

$ sudo mount nfs.example.com:/source_dir /opt/target_mount_dir

Many cloud providers, such as AWS and Azure, now offer NFS as a service. It’s a nice way to provide your storage-hungry application with a lot of space in a way that looks and feels almost like local attached storage. For media applications, however, a network-attached storage (NAS) setup is likely the better choice.

Sharing with Windows

If you have Windows machines in your local network and want to share it, you can use the Server Message Block (SMB) , a protocol initially developed at IBM in the 1980s, or its Microsoft-owned successor, Common Internet File System (CIFS) .

You would typically use Samba , the standard Windows interoperability suite of programs for Linux, to achieve the file sharing.

Advanced Network Topics

In this section, we discuss some advanced network protocols and tooling across the TCP/IP stack. Their usage is normally beyond the scope of a casual user. However, if you’re a developer or sys admin, you probably will want to be at least aware of them.

whois

whois is a client for the whois directory service that you can use to look up registration and user information. For example, if I want to find out who is behind the ietf.org domain (note that you can pay your domain registrar to keep that information private), I would do the following:

$ whois ietf.org 
% IANA WHOIS server
% for more information on IANA, visit http://www.iana.org
% This query returned 1 object

refer:        whois.pir.org

domain:       ORG

organisation: Public Interest Registry (PIR)
address:      11911 Freedom Drive 10th Floor,
address:      Suite 1000
address:      Reston, VA 20190
address:      United States

contact:      administrative
name:         Director of Operations, Compliance and Customer Support
organisation: Public Interest Registry (PIR)
address:      11911 Freedom Drive 10th Floor,
address:      Suite 1000
address:      Reston, VA 20190
address:      United States
phone:        +1 703 889 5778
fax-no:       +1 703 889 5779
e-mail:       [email protected]
...

1

Use whois to look up registration information about domain.

Dynamic Host Configuration Protocol

The Dynamic Host Configuration Protocol (DHCP) is a network protocol that enables automatic assignment of an IP address to a host. It’s a cli⁠ent​/server setup that removes the need for manually configuring network devices.

Setting up and managing a DHCP server is outside our scope, but you can use dhcpdump to scan for DHCP packets. For this, a device in your local network needs to join, trying to acquire an IP address, so you may need to be a bit patient to see something here (output shortened):

$ sudo dhcpdump -i wlp1s0 
  TIME: 2021-09-19 17:26:24.115
    IP: 0.0.0.0 (88:cb:87:c9:19:92) > 255.255.255.255 (ff:ff:ff:ff:ff:ff)
    OP: 1 (BOOTPREQUEST)
 HTYPE: 1 (Ethernet)
  HLEN: 6
  HOPS: 0
   XID: 7533fb70
   ...
OPTION:  57 (  2) Maximum DHCP message size 1500
OPTION:  61 (  7) Client-identifier         01:88:cb:87:c9:19:92
OPTION:  50 (  4) Request IP address        192.168.178.42
OPTION:  51 (  4) IP address leasetime      7776000 (12w6d)
OPTION:  12 ( 15) Host name                 MichaelminiiPad
...

1

Using dhcpdump , sniff DHCP packets on interface wlp1s0 .

Network Time Protocol

The Network Time Protocol (NTP) is for synchronizing clocks of computers over a network. For example, using the ntpq command , a standard NTP query program, you could make an explicit time server query like so:

 $ ntpq -p 
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 0.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 1.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 2.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 3.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 ntp.ubuntu.com  .POOL.          16 p    -   64    0    0.000    0.000   0.000
 ...
 ntp17.kashra-se 90.187.148.77    2 u    7   64    1   27.482   -3.451   2.285
 golem.canonical 17.253.34.123    2 u   13   64    1   20.338    0.057   0.000
 chilipepper.can 17.253.34.123    2 u   12   64    1   19.117   -0.439   0.000
 alphyn.canonica 140.203.204.77   2 u   14   64    1   91.462   -0.356   0.000
 pugot.canonical 145.238.203.14   2 u   13   64    1   20.788    0.226   0.000

1

With the -p option, show a list of peers known to the machine, including their state.

Usually, NTP works in the background, managed by systemd and other daemons, so you are unlikely to need to manually query it.

Wireshark and tshark

If you want to do low-level network traffic analysis—that is, you want to see exactly the packets across the stack—you can use either the command-line tool tshark or its GUI-based version, wireshark .

For example, after finding out via ip link that I have a network interface called wlp1s0 , I capture traffic there (output edited to fit):

$ sudo tshark -i wlp1s0 tcp 
Running as user "root" and group "root". This could be dangerous.
Capturing on 'wlp1s0'
    1 0.000000000 192.168.178.40 → 34.196.251.55 TCP 66 47618 → 443
    [ACK] Seq=1 Ack=1 Win=501 Len=0 TSval=3796364053 TSecr=153122458
    2 0.111215098 34.196.251.55 → 192.168.178.40 TCP 66
    [TCP ACKed unseen segment] 443 → 47618 [ACK] Seq=1 Ack=2 Win=283
    Len=0 TSval=153167579 TSecr=3796227866
    ...
    8 7.712741925 192.168.178.40 → 185.199.109.153 HTTP 146 GET / HTTP/1.1 
    9 7.776535946 185.199.109.153 → 192.168.178.40 TCP 66 80 → 42000 [ACK]
    Seq=1 Ack=81 Win=144896 Len=0 TSval=2759410860 TSecr=4258870662
   10 7.878721682 185.199.109.153 → 192.168.178.40 TCP 2946 HTTP/1.1 200 OK
   [TCP segment of a reassembled PDU]
   11 7.878722366 185.199.109.153 → 192.168.178.40 TCP 2946 80 → 42000
   [PSH, ACK] Seq=2881 Ack=81 Win=144896 Len=2880 TSval=2759410966 \
   TSecr=4258870662
   [TCP segment of a reassembled PDU]
   ...

1

Use tshark to capture network traffic on network interface wlp1s0 and only look at TCP traffic.

2

In another session, I issued a curl command to trigger an HTTP session, in which application layer interaction starts. You could also use the less powerful but on the other hand more widely available tcpdump for this task.

Other Advanced Tooling

There are a number of advanced network-related tools out there you may find useful, including but not limited to the following:

socat

Establishes two bidirectional byte streams and enables the transferring of data between the endpoint.

geoiplookup

Allows you to map an IP to a geographic region.

Tunnels

An easy-to-use alternative to VPNs and other site-to-site networking solutions. Enabled by such tools as inlets .

BitTorrent

A peer-to-peer system that groups files into a package called a torrent . Check out some clients to decide if this is something for your toolbox.

Conclusion

In this chapter, we defined common network terms, from the hardware level, such as NICs, to the TCP/IP stack, to application-layer, user-facing components, such as HTTP.

Linux provides a powerful, standards-based implementation of the TCP/IP stack that you can use programmatically (for example, sockets) and in the context of setting up and querying (usually with the ip command).

We further discussed application-layer protocols and interfaces that make up most of the daily (network-related) flows. Your command-line friends here include curl for transfer and dig for DNS lookups.

If you want to dive deeper into networking topics, check out the following resources:

The TCP/IP stack

DNS

Application layer and advanced networking

With that, we’re ready to move on to the next topic in the book: using observability to avoid flying blind.