Address of the server

The first thing we need is an address. A socket address consists of an IP address and a port number. We'll use IPv4 in this book because it's widely supported. In Chapter 6Reactive Microservices – Increasing Capacity and Performance, where we'll discuss scaling and the intercommunication of microservices, I'll show a few examples using IPv6.

The standard Rust library contains an IpAddr type to represent the IP address. We'll use the SocketAddr struct, which contains both the IpAddr and the u16 for the port number. We can construct the SocketAddr from a tuple of the ([u8; 4], u16) type. Add the following code to our main function:

let addr = ([127, 0, 0, 1], 8080).into();

We used an implementation of the impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr trait here, which, in turn, uses impl From<[u8; 4]> for IpAddr. This lets us use the .into() method call to construct a socket address from the tuple. Similarly, we can create new SocketAddr instances with a constructor. In production applications, we will parse the socket addresses from external strings (command-line parameters or environment variables), and if no variants are set, we'll create SocketAddr from a tuple with default values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.151