TCP and UDP Using Rust
local graph
Chapter 3 — TCP and UDP Using Rust
Section titled “Chapter 3 — TCP and UDP Using Rust”Being a system programming language, the Rust Standard Library has support for interacting with the network stack. All the networking-related functionality is located in the std::net namespace; reading and writing to sockets also uses Read and Write traits from std::io. Some of the most important structures here are IpAddr, which represents a generic IP address that can either be v4 or v6, SocketAddr, which represents a generic socket address (a combination of an IP and a port on a host), TcpListener and TcpStream for communicating over TCP, UdpSocket for UDP, and more. Currently, the standard library does not provide any APIs to deal with the network stack at a lower level. While this might change in the future, a number of crates fill that gap. The most important of these is libpnet, which provides a set of APIs for lower-level networking.
Some other important crates for networking are net2 and socket2. These were meant to be incubators for APIs that might be moved to the standard library. Some of the functionality here is ported to Rust core repo when it is deemed to be useful and stable enough. Unfortunately, this doesn’t work out as planned in all cases. On the whole, the community now suggests using the tokio ecosystem of crates for writing high-performance networking applications that do not require fine-grained control of socket semantics. Note that tokio is not in the scope of this chapter, and that we will cover it in a following chapter.
In this chapter, we will cover the following topics:
- What a simple multithreaded TCP client and server looks like in Rust
- Writing a simple multithreaded UDP client and server
- A number of functionalities in std::net
- Learning how to use net2, ipnetwork, and libpnet
For the sake of simplicity, all code in this chapter will deal with IPv4 only. Extending the given examples to IPv6 should be trivial.
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:
use std::net::{TcpListener, TcpStream};use std::thread;
use std::io::{Read, Write, Error};
// Handles a single clientfn handle_client(mut stream: TcpStream) -> Result<(), Error> { println!("Incoming connection from: {}", stream.peer_addr()?); let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf)?; if bytes_read == 0 { return Ok(()); } stream.write(&buf[..bytes_read])?; }}
fn main() { let listener = TcpListener::bind("0.0.0.0:8888") .expect("Could not bind"); for stream in listener.incoming() { match stream { Err(e) => { eprintln!("failed: {}", e) } Ok(stream) => { thread::spawn(move || { handle_client(stream) .unwrap_or_else(|error| eprintln!("{:?}", error)); }); } } }}In our main function, we create a new TcpListener, which in Rust, represents a TCP socket that is listening for incoming connections from clients. For our example, we have hardcoded the local address and the port; the local address being set to 0.0.0.0 tells the kernel to bind this socket to all available interfaces on this host. Setting a well-known port here is important since we will need to know that to connect from the client. In a real application, this should be a configurable parameter taken from the CLI or a configuration file. We call bind on the local IP and port pair to create a local listening socket. As discussed earlier, our given choice of IP will bind this socket to all interfaces available on the host, on port 8888. As a result, any client that can reach a network connected to this host will be able to talk to this host. As we have seen in the last chapter, the expect function returns the listener if there were no errors. If that is not the case, it panics with the given message. Panicking on failing to bind to the port is actually okay here, since if that fails, there is no way the server will continue working. The incoming method on listener returns an iterator over streams that have connected to the server. We loop over them and check if any of those have encountered an error. In that case, we can print the error and move on to the next connected client. Note that panicking in this case is not appropriate since the server can function fine if some of the clients run into errors for some reason.
Now, we must read data from each of the clients in an infinite loop. But running an infinite loop in the main thread will block it and no other clients will be able to connect. That behavior is definitely not desirable. Thus, we must spawn a worker thread to handle each client connection. The logic of reading from each stream and writing it back is encapsulated in the function called handle_client. Each thread receives a closure that calls this function. This closure must be a move closure, since this must read a variable (stream) from the enclosing scope. In the function, we print the remote endpoint address and port, and then define a buffer to hold data temporarily. We also make sure that the buffer is zeroed out. We then run an infinite loop in which we read all data in the stream. The read method in the stream returns the length of the data it has read. It can return zero in two cases, if it has reached the end of the stream or if the given buffer was zero in length. We know for sure that the second case is not true. Thus, we break out of the loop (and the function) when the read method returns a zero. In that case, we return a Ok(). We then write the same data back to the stream using the slice syntax. Note that we have used eprintln! to output errors. This macro writes the given string to a standard error, and has been stabilized recently.
One might notice the apparent lack of error handling in reading from and writing to the stream. But that is not actually the case. We have used the ? operator to handle errors in these invocations. This operator unwraps the result to an Ok if everything was fine; otherwise, it does an early return of the error to the calling function. Given this setup, the return type of the function must be either the empty type, to handle success cases, or the io::Error type, to handle error cases. Note that it might be a good idea to implement custom errors in such cases and return those instead of built-in errors. Also note that the ? operator cannot be used in the main function currently since the main function does not return a Result.
Rust recently accepted an RFC which proposes the ability to use the ? operator in the main function.
Interacting with the server from the terminal is easy. When we run the server on a Linux machine and nc on another terminal, any text entered to nc should be echoed back. Note that if the client and the server are running on the same node, we can use 127.0.0.1 as the server address:
$ nc <server ip> 8888testtestfoobarfoobarfoobarbazfoobarbaz^CWhile using nc to interact with the server is fine, it is much more fun to write a client from scratch. In this section, we will see what a simple TCP client might look like. This client will read input from stdin as a string and send it over to the server. When it gets back a reply, it will print that in stdout. In our example here, the client and the server are running on the same physical host, so we can use 127.0.0.1 as the server address:
use std::net::TcpStream;use std::str;use std::io::{self, BufRead, BufReader, Write};
fn main() { let mut stream = TcpStream::connect("127.0.0.1:8888") .expect("Could not connect to server"); loop { let mut input = String::new(); let mut buffer: Vec<u8> = Vec::new(); io::stdin().read_line(&mut input) .expect("Failed to read from stdin"); stream.write(input.as_bytes()) .expect("Failed to write to server");
let mut reader = BufReader::new(&stream);
reader.read_until(b'\n', &mut buffer) .expect("Could not read into buffer"); print!("{}", str::from_utf8(&buffer) .expect("Could not write buffer as string")); }}In this case, we start with importing all required libraries. We then set up a connection to the server using TcpStrem::connect, which takes in the remote endpoint address as a string. Like all TCP connections, the client needs to know the remote IP and port to connect. In case setting up the connection fails, we will abort our program with an error message. We then start an infinite loop, in which we will initialize an empty string to read user input locally and a vector of u8 to read responses from the server. Since a vector in Rust grows as necessary, we will not need to manually chunk the data at each iteration. The read_line function reads a line from standard input and stores it in the variable called input. Then, it is written to the connection as a stream of bytes. At this point, if everything worked as expected, the server should have sent back a response. We will read that using a BufReader that takes care of chunking the data internally. This also makes reading more efficient since there will not be more system calls than necessary. The read_until method reads the data in our buffer, which grows as needed. Finally, we can print out the buffer as a string, which has been converted using the from_utf8 method.
Running the client is easy, and as expected, behaves exactly like nc:
$ rustc tcp-client.rs && ./tcp-clienttesttestfoobarfoobarfoobarbazfoobarbaz^CReal-world applications are often more complex than this. A server might need some time to process the input before serving back the response. Let’s simulate that by sleeping for a random amount of time in the handle_client function; the main function will remain exactly the same as the previous example. The first step is to create our project using cargo:
$ cargo new --bin tcp-echo-randomNote that we will need to add the rand crate in our Cargo.toml, as shown in the following code snippet:
[package]name = "tcp-echo-random"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]rand = "0.3.17"Having set up our dependencies, let’s modify the handle_client function to sleep for a random delay before sending the response back:
extern crate rand;
use std::net::{TcpListener, TcpStream};use std::thread;use rand::{thread_rng, Rng};use std::time::Duration;use std::io::{Read, Write, Error};
fn handle_client(mut stream: TcpStream) -> Result<(), Error> { let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf)?; if bytes_read == 0 { return Ok(()) } let sleep = Duration::from_secs(*thread_rng() .choose(&[0, 1, 2, 3, 4, 5]) .unwrap()); println!("Sleeping for {:?} before replying", sleep); std::thread::sleep(sleep); stream.write(&buf[..bytes_read])?; }}
fn main() { let listener = TcpListener::bind("127.0.0.1:8888").expect("Could not bind"); for stream in listener.incoming() { match stream { Err(e) => eprintln!("failed: {}", e), Ok(stream) => { thread::spawn(move || { handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error)); }); } } }}In our main file, we must declare a dependency on the rand crate and declare it as an extern crate. We use the thread_rng function to select an integer between zero and five randomly and then sleep for that time duration using std::thread::sleep. On the client side, we will set read and connect timeouts, since replies won’t be instantaneous from the server:
use std::net::TcpStream;use std::str;use std::io::{self, BufRead, BufReader, Write};use std::time::Duration;use std::net::SocketAddr;
fn main() { let remote: SocketAddr = "127.0.0.1:8888".parse().unwrap(); let mut stream = TcpStream::connect_timeout(&remote, Duration::from_secs(1)) .expect("Could not connect to server"); stream.set_read_timeout(Some(Duration::from_secs(3))) .expect("Could not set a read timeout"); loop { let mut input = String::new(); let mut buffer: Vec<u8> = Vec::new(); io::stdin().read_line(&mut input).expect("Failed to read from stdin"); stream.write(input.as_bytes()).expect("Failed to write to server");
let mut reader = BufReader::new(&stream);
reader.read_until(b'\n', &mut buffer) .expect("Could not read into buffer"); print!("{}", str::from_utf8(&buffer) .expect("Could not write buffer as string")); }}Here, we use set_read_timeout to set the timeout to three seconds. Thus, if the server sleeps for more than three seconds, the client will abort the connection. This function is curious since it takes in Option<Duration> to be able to specify a Duration that is None. Hence, we will need to wrap our Duration in a Some before passing to this function. Now, if we open two sessions, running the server using cargo in one and the client in another, here is what we’ll see; the server prints how long it slept, for each client it accepts:
$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running \`target/debug/tcp-echo-random\`Sleeping for Duration { secs: 2, nanos: 0 } before replyingSleeping for Duration { secs: 1, nanos: 0 } before replyingSleeping for Duration { secs: 1, nanos: 0 } before replyingSleeping for Duration { secs: 5, nanos: 0 } before replyingOn the client side, we have a single file (not a cargo project) that we will build using rustc and run the executable directly after compiling:
$ rustc tcp-client-timeout.rs && ./tcp-client-timeouttesttestfoofoobarbarbazthread 'main' panicked at 'Could not read into buffer: Error { repr: Os { code: 35, message: "Resource temporarily unavailable" } }', src/libcore/result.rs:906:4note: Run with \`RUST_BACKTRACE=1\` for a backtrace.For the first three inputs, the server chose delays which were less than three seconds. The client got a response back within three seconds and did not abort the connection. For the last message, the delay was five seconds, which caused the client to abort reading.
There are a few semantic differences between the UDP server and the TCP server we wrote earlier. Unlike TCP, UDP does not have a stream structure. This derives from the semantic differences between the two protocols. Let’s take a look at what a UDP server might look like:
use std::thread;use std::net::UdpSocket;
fn main() { let socket = UdpSocket::bind("0.0.0.0:8888") .expect("Could not bind socket");
loop { let mut buf = [0u8; 1500]; let sock = socket.try_clone().expect("Failed to clone socket"); match socket.recv_from(&mut buf) { Ok((_, src)) => { thread::spawn(move || { println!("Handling connection from {}", src); sock.send_to(&buf, &src) .expect("Failed to send a response"); }); }, Err(e) => { eprintln!("couldn't recieve a datagram: {}", e); } } }}As with TCP, we start with binding to the local address on a given port and we handle the possibility that binding can fail. Since UDP is a connectionless protocol, we will not need to do a sliding window to read all the data. Thus, we can just allocate a static buffer of a given size. It will be a better idea to dynamically detect the MTU of the underlying network card and set the buffer size to be that, since that is the maximum size each UDP packet can have. However, since MTU for a common LAN is around 1,500, we can get away with allocating a buffer of that size here. The try_clone method clones the given socket and returns a new one, which is moved into the closure.
We then read from the socket, which returns the length of the data read and the source in the Ok() case. We then spawn a new thread, in which we write back the same buffer to the given socket. For anything that can fail, we will need to handle the error like we did for the TCP server.
Interacting with this server is exactly the same as last time—using nc. The only difference is that in this case, we will need to pass the -u flag to force nc to make it use only UDP. Take a look at the following example:
$ nc -u 127.0.0.1 8888testtesttesttest^CNow, let’s write a simple UDP client to achieve the same results. As we will see, there are some subtle differences between the TCP server and this:
use std::net::UdpSocket;use std::{str,io};
fn main() { let socket = UdpSocket::bind("127.0.0.1:8000") .expect("Could not bind client socket"); socket.connect("127.0.0.1:8888") .expect("Could not connect to server"); loop { let mut input = String::new(); let mut buffer = [0u8; 1500]; io::stdin().read_line(&mut input) .expect("Failed to read from stdin"); socket.send(input.as_bytes()) .expect("Failed to write to server");
socket.recv_from(&mut buffer) .expect("Could not read into buffer"); print!("{}", str::from_utf8(&buffer) .expect("Could not write buffer as string")); }}There is a major difference between this basic client and the TCP client we saw in the last section. In this case, it is absolutely essential to bind to a client-side socket first before connecting to the server. Once that is done, the rest of the example is essentially the same. Running it on the client side and the server side produces similar results like the TCP case. Here is a session on the server side:
$ rustc udp-echo-server.rs && ./udp-echo-serverHandling connection from 127.0.0.1:8000Handling connection from 127.0.0.1:8000Handling connection from 127.0.0.1:8000^CHere is what we see on the client side:
$ rustc udp-client.rs && ./udp-clienttesttestfoofoobarbar^CThe UdpSocket type has a number of methods that the corresponding TCP types do not. Of these, the most interesting ones are for multicasting and broadcasting. Let’s look at how multicasting works with an example server and client. For this example, we will combine the client and the server in one file. In the main function, we will check whether a CLI argument has been passed. If there has, we will run the client; otherwise, we will run the server. Note that the value of the argument will not be used; it will be treated as a Boolean:
use std::{env, str};use std::net::{UdpSocket, Ipv4Addr};
fn main() { let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap(); let port: u16 = 6000; let any = "0.0.0.0".parse().unwrap(); let mut buffer = [0u8; 1600]; if env::args().count() > 1 { // client case let socket = UdpSocket::bind((any, port)) .expect("Could not bind client socket"); socket.join_multicast_v4(&mcast_group, &any) .expect("Could not join multicast group"); socket.recv_from(&mut buffer) .expect("Failed to write to server"); print!("{}", str::from_utf8(&buffer) .expect("Could not write buffer as string")); } else { // server case let socket = UdpSocket::bind((any, 0)) .expect("Could not bind socket"); socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)) .expect("Failed to write data"); }}Both the client and the server parts here are mostly similar to what we discussed before. One difference is that the join_multicast_v4 call makes the current socket join a multicast group with the address passed. For both the server and the client, we do not specify a single address while binding. Instead, we use the special address 0.0.0.0 that denotes any available address. This is equivalent to passing INADDR_ANY to the underlying setsockopt call. In the server case, we send it to the multicast group instead. Running this is a bit more tricky. Since there is no way to set SO_REUSEADDR and SO_REUSEPORT in the standard library, we will need to run the client on multiple different machines and the server on another. For this to work, all of those need to be in the same network and the address of the multicast group needs to be a valid multicast address (the first four bits should be 1110). The UdpSocket type also supports leaving multicast groups, broadcasting, and so on. Note that broadcasting does not make sense for TCP since it is a connection between two hosts by definition.
Running the previous example is simple; on one host, we will run the server, and on the other, the client. Given this setup, the output should look like this on the server side:
$ rustc udp-multicast.rs && ./udp-multicast serverHello world!Another important type in the standard library is IpAddr, which represents an IP address. Not surprisingly, it is an enum with two variants, one for v4 addresses and the other for v6 addresses. All of these types have methods to classify addresses according to their types (global, loopback, multicast, and so on). Note that a number of these methods are not stabilized yet and hence are only available in the nightly compiler. They are behind a feature flag named ip which must be included in the crate root so that you can use those methods. A closely related type is SocketAddr, which is a combination of an IP address and a port number. Thus, this also has two variants, one for v4 and one for v6. Let’s look at some examples:
#![feature(ip)]
use std::net::{IpAddr, SocketAddr};
fn main() { // construct an IpAddr from a string and check it // represents the loopback address let local: IpAddr = "127.0.0.1".parse().unwrap(); assert!(local.is_loopback());
// construct a globally routable IPv6 address from individual octets // and assert it is classified correctly let global: IpAddr = IpAddr::from([0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1]); assert!(global.is_global());
// construct a SocketAddr from a string an assert that the underlying // IP is a IPv4 address let local_sa: SocketAddr = "127.0.0.1:80".parse().unwrap(); assert!(local_sa.is_ipv4());
// construct a SocketAddr from a IPv6 address and a port, assert that // the underlying address is indeed IPv6 let global_sa = SocketAddr::new(global, 80u16); assert!(global_sa.is_ipv6());}The feature(ip) declaration is necessary since the is_global function is not stabilized yet. This example does not produce any output since all asserts should evaluate to true.
A common functionality is that of a DNS lookup, given a hostname. Rust does this using the lookup_host function that returns the LookupHost type, which is actually an iterator over DNS responses. Let’s look at how this can be used. This function is gated by the looup_host flag and must be included to use this function with the nightly compiler:
#![feature(lookup_host)]
use std::env;use std::net::lookup_host;
fn main() { let args: Vec<_> = env::args().collect(); if args.len() != 2 { eprintln!("Please provide only one host name"); std::process::exit(1); } else { let addresses = lookup_host(&args[1]).unwrap(); for address in addresses { println!("{}", address.ip()); } }}Here, we read a CLI argument and exit if we were not given exactly one name to resolve. Otherwise, we call lookup_host with the given hostname. We iterate over the returned results and print the IP of each. Note that each of the returned results is of type SocketAddr; since we are only interested in the IP, we extract that using the ip() method. This function corresponds to the getaddrinfo call in libc, and thus it returns only A and AAAA record types. Running this is as expected:
$ rustc lookup-host.rs && ./lookup-host google.com2a00:1450:4009:810::200e216.58.206.110Currently, reverse DNS lookup is not possible in the standard library. In the next section, we will discuss some crates in the ecosystem that can be used for the advanced networking functionality. For instance, the trust-dns crate supports interacting with DNS servers in more detail, and it also supports querying all record types and also reverse DNS.
A careful reader might have noticed that a lot of common networking-related functionalities are missing from the standard library. For instance, there is no way to deal with IP networks (CIDRs). Let’s look at how the ipnetwork crate helps with that. Since we are going to use an external crate, the example has to be in a cargo project. We will need to add it as a dependency to Cargo.toml. Let’s start by setting up a project:
$ cargo new --bin ipnetwork-exampleThis generates a Cargo.toml file that we need to modify to declare our dependency. Once we do that, it should look like this:
[package]name = "ipnetwork-example"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]ipnetwork = "0.12.7"Having set up the project, let’s look at our main function:
extern crate ipnetwork;
use std::net::Ipv4Addr;use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
fn main() { let net = IpNetwork::new("192.168.122.0".parse().unwrap(), 22) .expect("Could not construct a network"); let str_net: IpNetwork = "192.168.122.0/22".parse().unwrap();
assert!(net == str_net); assert!(net.is_ipv4());
let net4: Ipv4Network = "192.168.121.0/22".parse().unwrap(); assert!(net4.size() == 2u64.pow(32 - 22)); assert!(net4.contains(Ipv4Addr::new(192, 168, 121, 3)));
let _net6: Ipv6Network = "2001:db8::0/96".parse().unwrap(); for addr in net4.iter().take(10) { println!("{}", addr); }}The first two lines show two different ways of constructing IpNetwork instances, either using the constructor or by parsing a string. The next assert makes sure they are indeed identical. The assert after that ensures that the network we created is a v4 network. Next, we specifically create Ipv4Network objects and as expected, the size of the network matches 2^(32 - prefix). The next assert makes sure the contains method works correctly for an IP in that network. We then create a Ipv6Network, and since all of these types implement the iterator protocol, we can iterate over the network and print individual addresses in a for loop. Here is the output that we should see by running the last example:
$ cargo run Compiling ipnetwork v0.12.7 Compiling ipnetwork-example v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/chapter3/ipnetwork-example) Finished dev [unoptimized + debuginfo] target(s) in 1.18 secs Running \`target/debug/ipnetwork-example\`192.168.120.0192.168.120.1192.168.120.2192.168.120.3192.168.120.4192.168.120.5192.168.120.6192.168.120.7192.168.120.8192.168.120.9The standard library also lacks fine-grained control over sockets and connections, one example being the ability to set SO_REUSEADDR, as we described before. The primary reason for this is that the community has not been able to reach a strong consensus on how to best expose these features while maintaining a clean API. A useful library in this context is mio, which provides an alternative to thread-based concurrency. mio essentially runs an event loop where all parties register. When there is an event, every listener is alerted and they have the option to handle that event. Let’s look at the following example. Like last time, we will need to set up the project using cargo:
$ cargo new --bin mio-exampleThe next step is to add mio as a dependency; the Cargo.toml file should look like this:
[package]name = "mio-example"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]mio = "0.6.11"Like all other cargo projects, we will need to declare mio as a dependency in Cargo.toml and pin it to a specific version so that cargo can download it and link it against our app:
extern crate mio;
use mio::*;use mio::tcp::TcpListener;
use std::net::SocketAddr;use std::env;
// This will be later used to identify the server on the event loopconst SERVER: Token = Token(0);
// Represents a simple TCP server using miostruct TCPServer { address: SocketAddr,}
// Implementation for the TCP serverimpl TCPServer { fn new(port: u32) -> Self { let address = format!("0.0.0.0:{}", port) .parse::<SocketAddr>().unwrap();
TCPServer { address, } }
// Actually binds the server to a given address and runs it // This function also sets up the event loop that dispatches // events. Later, we use a match on the token on the event // to determine if the event is for the server. fn run(&mut self) { let server = TcpListener::bind(&self.address) .expect("Could not bind to port"); let poll = Poll::new().unwrap(); poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap();
let mut events = Events::with_capacity(1024); loop { poll.poll(&mut events, None).unwrap();
for event in events.iter() { match event.token() { SERVER => { let (_stream, remote) = server.accept().unwrap(); println!("Connection from {}", remote); } _ => { unreachable!(); } } } } }}
fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { eprintln!("Please provide only one port number as argument"); std::process::exit(1); } let mut server = TCPServer::new(args[1].parse::<u32>() .expect("Could not parse as u32")); server.run();}Unlike our previous examples, this is a TCP server that just prints the client’s source IP and port. In mio, every listener on the event loop is assigned a token, which can then be used to differentiate between the listeners when an event is delivered. We define a struct for our server (TCPServer) in its constructor, and we bind to all local addresses and return an instance of the struct. The run method of that struct binds the socket to the given socket address; it then uses the Poll struct to instantiate the event loop.
It then registers the server socket, with a token on the instance. We also indicate that we should be alerted when the event is ready for reading or writing. Lastly, we indicate that we want edge-triggered events only, which means that the event should be wholly consumed when it is received, otherwise subsequent calls on the same token might block it. We then set up an empty container for our events. Having done all the boilerplate, we enter an infinite loop and start polling with the events container we just created. We loop over the list of events, and if any of the event’s tokens match the server’s token, we know it is meant for the server. We can then accept the connection and print the remote end’s information. We then go back to the next event, and so on. In our main function, we first deal with CLI arguments, making sure that we passed a port number as an integer. Then, we instantiate the server and call the run method on it.
Here is a sample session on running the server when two clients are connected to it. Note that either nc or the TCP clients from earlier can be used to connect to this server:
$ cargo run 4321 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running \`target/debug/mio-example 4321\`Connection from 127.0.0.1:60955Connection from 127.0.0.1:60956^CSome other major things that are missing from the standard library and the crates discussed here is the ability to work with the physical network device, a nicer API to craft and parse packets, and so on. One crate that helps in dealing with lower level network-related things in libpnet. Let’s write a small packet dumper using it:
$ cat Cargo.toml[package]name = "pnet-example"version = "0.1.0"authors = ["Foo Bar <[email protected]>"]
[dependencies]pnet = "0.20.0"We initialize our Cargo project like this:
$ cargo new --bin pnet-exampleWe then add pnet as a dependency, pinning it to a specific version (the latest one currently available). We can then move on to our source, which should look like this:
extern crate pnet;
use pnet::datalink::{self, NetworkInterface};use pnet::datalink::Channel::Ethernet;use pnet::packet::ethernet::{EtherTypes, EthernetPacket};use pnet::packet::ipv4::Ipv4Packet;use pnet::packet::tcp::TcpPacket;use pnet::packet::ip::IpNextHeaderProtocols;use pnet::packet::Packet;
use std::env;
// Handles a single ethernet packetfn handle_packet(ethernet: &EthernetPacket) { match ethernet.get_ethertype() { EtherTypes::Ipv4 => { let header = Ipv4Packet::new(ethernet.payload()); if let Some(header) = header { match header.get_next_level_protocol() { IpNextHeaderProtocols::Tcp => { let tcp = TcpPacket::new(header.payload()); if let Some(tcp) = tcp { println!( "Got a TCP packet {}:{} to {}:{}", header.get_source(), tcp.get_source(), header.get_destination(), tcp.get_destination() ); } } _ => println!("Ignoring non TCP packet"), } } } _ => println!("Ignoring non IPv4 packet"), }}
fn main() { let interface_name = env::args().nth(1).unwrap();
// Get all interfaces let interfaces = datalink::interfaces(); // Filter the list to find the given interface name let interface = interfaces .into_iter() .filter(|iface: &NetworkInterface| iface.name == interface_name) .next() .expect("Error getting interface");
let (_tx, mut rx) = match datalink::channel(&interface, Default::default()) { Ok(Ethernet(tx, rx)) => (tx, rx), Ok(_) => panic!("Unhandled channel type"), Err(e) => { panic!( "An error occurred when creating the datalink channel: {}",e ) } };
// Loop over packets arriving on the given interface loop { match rx.next() { Ok(packet) => { let packet = EthernetPacket::new(packet).unwrap(); handle_packet(&packet); } Err(e) => { panic!("An error occurred while reading: {}", e); } } }}Like always, we start with declaring pnet as an external crate. We then import a bunch of things that we will use later. We take in the name of the interface we should sniff as a CLI argument. The datalink::interfaces() gets us a list of all available interfaces in the current host, and we filter that list by the name of the interface we were given. In case we do not find a match, we throw an error and exit. The datalink::channel() call gives us a channel to send and receive packets. In this case, we do not care about the sending end since we are just interested in sniffing packets. We match on the returned channel type to make sure we work with Ethernet only. The receiving end of the channel, rx, gives us an iterator that yields packets on each next() call.
The packets are then passed to the handle_packet function, which extracts relevant information and prints those. For this toy example, we will only deal with IPv4-based TCP packets. A real network will obviously get IPv6 and ICMP packets with UDP and TCP. All those combinations will be ignored here.
In the handle_packet function, we match on the ethertype of the packet to make sure we only process IPv4 packets. Since the whole payload of the Ethernet packet is the IP packet (refer to Chapter 1, Introduction to Client/Server Networking), we construct an IP packet from the payload. The get_next_level_protocol() call returns the transport protocol, and if that matches TCP, we construct a TCP packet from the payload of the preceding layer. At this point, we can print the source and destination port from the TCP packet. The source and destination IP will be in the enclosing IP packet. An example run is shown in the following code block. We need to pass the name of the interface to listen on to our program as command line arguments. Here is how we can get the interface name in Linux:
$ ip a1: 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 forever2: enp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether f4:4d:30:ac:88:ee brd ff:ff:ff:ff:ff:ff inet 192.168.5.15/22 brd 192.168.7.255 scope global enp1s0 valid_lft forever preferred_lft forever inet6 fe80::58c6:9ccc:e78c:caa6/64 scope link valid_lft forever preferred_lft foreverFor this example, we will ignore the loopback interface l0 since it does not receive a lot of traffic, and use the other interface enp1s0. We will also run this example with root privileges (using sudo) since it need to access the network device directly.
The first step is to build the project using cargo and the run the executable. Note that the exact output of this example might be a bit different, depending on what packets arrive:
$ cargo build$ sudo ./target/debug/pnet-example enp1s0Got a TCP packet 192.168.0.2:53041 to 104.82.249.116:443Got a TCP packet 104.82.249.116:443 to 192.168.0.2:53041Got a TCP packet 192.168.0.2:53064 to 17.142.169.200:443Got a TCP packet 192.168.0.2:53064 to 17.142.169.200:443Got a TCP packet 17.142.169.200:443 to 192.168.0.2:53064Got a TCP packet 17.142.169.200:443 to 192.168.0.2:53064Got a TCP packet 192.168.0.2:53064 to 17.142.169.200:443Got a TCP packet 192.168.0.2:52086 to 52.174.153.60:443Ignoring non IPv4 packetGot a TCP packet 52.174.153.60:443 to 192.168.0.2:52086Got a TCP packet 192.168.0.2:52086 to 52.174.153.60:443Ignoring non IPv4 packetIgnoring non IPv4 packetIgnoring non IPv4 packetIgnoring non IPv4 packetIn the previous section, we saw how the DNS-related functionality in the standard library is rather limited. One crate that is widely popular for DNS-related things in trust-dns. Let’s look at an example of using this for querying a given name. Let’s start with the empty project:
$ cargo new --bin trust-dns-exampleWe will then add the versions of required crates in Cargo.toml first:
[package]name = "trust-dns-example"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]trust-dns-resolver = "0.6.0"trust-dns = "0.12.0"Our app depends on trust-dns for DNS-related things. As usual, we will add it to our Cargo.toml before using it in our app:
extern crate trust_dns_resolver;extern crate trust_dns;
use std::env;
use trust_dns_resolver::Resolver;use trust_dns_resolver::config::*;
use trust_dns::rr::record_type::RecordType;
fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { eprintln!("Please provide a name to query"); std::process::exit(1); } let resolver = Resolver::new(ResolverConfig::default(), ResolverOpts::default()).unwrap();
// Add a dot to the given name let query = format!("{}.", args[1]);
// Run the DNS query let response = resolver.lookup_ip(query.as_str()); println!("Using the synchronous resolver"); for ans in response.iter() { println!("{:?}", ans); }
println!("Using the system resolver"); let system_resolver = Resolver::from_system_conf().unwrap(); let system_response = system_resolver.lookup_ip(query.as_str()); for ans in system_response.iter() { println!("{:?}", ans); }
let ns = resolver.lookup(query.as_str(), RecordType::NS); println!("NS records using the synchronous resolver"); for ans in ns.iter() { println!("{:?}", ans); }}We set up all required imports and extern crate declarations. Here, we expect to get the name to resolve as a CLI argument, and if everything goes well, it should be in args[1]. This crate supports two types of synchronous DNS resolver. Resolver::new creates a synchronous resolver, and with default options, it will use Google’s public DNS as upstream servers. The Resolver::from_system_conf creates a synchronous resolver with configurations from the system’s resolv.conf. Thus, this second option is only available on Unix systems. Before we pass the query to the resolver, we format it to FQDN by appending a . to the name, using the format! macro. We pass the query using the lookup_ip function, which then returns an iterator over the answers of the DNS question. Once we get that, we can iterate over it and print out each answer. As the name suggests, the lookup_ip function only looks up A and AAAA records. There is a more general lookup function that can take in a record type to query. In the last step, we want to get all NS records for the given name. Once we get back an answer, we loop over it and print the results.
trust-dns also supports a tokio-based asynchronous DNS resolver.
An example session will look like this:
$ cargo run google.com Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running \`target/debug/trust-dns-example google.com\`Using the synchronous resolverLookupIp(Lookup { rdatas: [AAAA(2a00:1450:4009:811::200e), A(216.58.206.142)] })Using the system resolverLookupIp(Lookup { rdatas: [A(216.58.206.110), AAAA(2a00:1450:4009:810::200e)] })NS records using the synchronous resolverLookup { rdatas: [NS(Name { is_fqdn: true, labels: ["ns3", "google", "com"] }), NS(Name { is_fqdn: true, labels: ["ns1", "google", "com"] }), NS(Name { is_fqdn: true, labels: ["ns4", "google", "com"] }), NS(Name { is_fqdn: true, labels: ["ns2", "google", "com"] })] }In this example, all prints are using the debug representation of the structures. A real application will want to format these as required.
This chapter was a short introduction to the basic networking functionality in Rust. We started with given functionality in std::net, and we wrote a few TCP and UDP servers using those. We then looked at some other utilities in the same namespace. At the end, we went over examples of a number of crates which are aimed at extending the standard library’s functionality around networking. Bear in mind that it is always possible to just use the libc crate to write networking code, which is based on POSIX-compatible networking code with access to fine-grained control over sockets and network devices. The problem with this approach is that the code might be unsafe, breaking Rust’s guarantee of safety. Another crate called nix aims to provide libc’s functionality native Rust so that it preserves all the memory and type safety guarantees that the compiler provides: this might be a useful alternative for someone who needs very fine control over networking.
In the next chapter, we will look at how to handle data once we receive it in a server or a client using a number of serialization/de-serialization methods in the Rust ecosystem.