Hash based IP Routing in Rust
A exact-match IP routing implementation using a HashMaps in Rust
Like all my previous newsletters, I don’t want to explain why I wanted to implement a routing table. However, I would suggest you check my previous posts and share them with your friends.
If you like my newsletter, then get the Substack app.
What is IP Routing?
In simple terms, IP routing is all about sending a packet to the right destination. In this world with an Internet that is so wide, every device must know where to send the packet, so that it can reach its desired location.
In the figure, the device (like a server or a router) receives a packet (doesn’t matter the source), and the device recognizes that the destination of the packet should be 192.168.1.16. Referring to the routing table it decides to send the packet to interface eth0. The routing table has an interface (next hop) for each network address.
Understanding IP Address Matching
Let's dive into how IP matching is done. Firstly, the IPv4 address contains 4 octets, we recognize the network address using the subnet mask. For e.g
So using the above matching technique let’s implement a Simple IP Routing table.
Implementation
We first need a HashMap which stores key-value pairs of the network address (key) and its corresponding interface values.
The most important methods that should be implemented are the insert and search method. The insert method allows us to add the network addresses and their interfaces to the table. The search method is used to get the interface (the next hop) values for a given destination IP.
The insert and search methods both use the network_address function to convert an IPv4 address to its corresponding network address using the subnet mask provided.
After we implement these methods and functions. We start by instantiating the Hash Routing table, adding the entries to the table and searching the table to get an exact match.
Although this works, it this not an implementation that can be used in the real world. Why? Because in the real-world scenario, we need to use Longest Prefix Matching. Th longest prefix matching can be used to identify the best match when there exist multiple matching network addresses.
Checkout the entire source code on Github: HashRT
Follow me on Linkedin: anvayabn
Please leave your comment, like and subscribe.