Book Image

Network Programming with Rust

By : Abhishek Chanda
Book Image

Network Programming with Rust

By: Abhishek Chanda

Overview of this book

Rust is low-level enough to provide fine-grained control over memory while providing safety through compile-time validation. This makes it uniquely suitable for writing low-level networking applications. This book is divided into three main parts that will take you on an exciting journey of building a fully functional web server. The book starts with a solid introduction to Rust and essential networking concepts. This will lay a foundation for, and set the tone of, the entire book. In the second part, we will take an in-depth look at using Rust for networking software. From client-server networking using sockets to IPv4/v6, DNS, TCP, UDP, you will also learn about serializing and deserializing data using serde. The book shows how to communicate with REST servers over HTTP. The final part of the book discusses asynchronous network programming using the Tokio stack. Given the importance of security for modern systems, you will see how Rust supports common primitives such as TLS and public-key cryptography. After reading this book, you will be more than confident enough to use Rust to build effective networking software
Table of Contents (11 chapters)

A Simple TCP server and client

Most networking examples start with an echo server. So, let's go ahead and write a basic echo server in Rust to see how all the pieces fit together. We will use the threading model from the standard library for handling multiple clients in parallel. The code is as follows:

// chapter3/

use std::net::{TcpListener, TcpStream};
use std::thread;

use std::io::{Read, Write, Error};

// Handles a single client
fn handle_client(mut stream: TcpStream) -> Result<(), Error> {
println!("Incoming connection from: {}", stream.peer_addr()?);
let mut buf = [0; 512];
loop {
let bytes_read = buf)?;
if bytes_read == 0 { return Ok(()); }

fn main() {
let listener = TcpListener::bind("")