8 Networking

 

This chapter covers

  • Implementing a networking stack
  • Handling multiple error types within local scope
  • When to use trait objects
  • Implementing state machines in Rust

This chapter describes how to make HTTP requests multiple times, stripping away a layer of abstraction each time. We start by using a user-friendly library, then boil that away until we’re left with manipulating raw TCP packets. When we’re finished, you’ll be able to distinguish an IP address from a MAC address. And you’ll learn why we went straight from IPv4 to IPv6.

You’ll also learn lots of Rust in this chapter, most of it related to advanced error handling techniques that become essential for incorporating upstream crates. Several pages are devoted to error handling. This includes a thorough introduction to trait objects.

Networking is a difficult subject to cover in a single chapter. Each layer is a fractal of complexity. Networking experts will hopefully overlook my lack of depth in treating such a diverse topic.

Figure 8.1 provides an overview of the topics that the chapter covers. Some of the projects that we cover include implementing DNS resolution and generating standards-compliant MAC addresses, including multiple examples of generating HTTP requests. A bit of a role-playing game is added for light relief.

Figure 8.1 Networking chapter map. The chapter incorporates a healthy mix of theory and practical exercises.

8.1 All of networking in seven paragraphs

8.2 Generating an HTTP GET request with reqwest

8.3 Trait objects

8.3.1 What do trait objects enable?

8.3.2 What is a trait object?

8.3.3 Creating a tiny role-playing game: The rpg project

8.4 TCP

8.4.1 What is a port number?

8.4.2 Converting a hostname to an IP address

8.5 Ergonomic error handling for libraries

8.5.1 Issue: Unable to return multiple error types

8.5.2 Wrapping downstream errors by defining our own error type