Routing is a primary function of IP. Datagrams are handed to IP from
UDP and TCP above, and from the NIC(s) below. Each datagram is labeled with a
source and destination IP address. IP examines the destination address on each
datagram, compares it to a locally maintained route table, and decides what
action to take. There are three possibilities for each datagram:
- It can be passed up to a protocol layer above IP
on the local host.
- It can be forwarded using one of the locally
- It can be discarded.
The route table maintains four different types of routes. They are
listed below in the order that they are searched for a match:
- Host (a route to a single, specific destination IP
- Subnet (a route to a subnet)
- Network (a route to an entire network)
- Default (used when there is no other match)
To determine a single route to use to forward an IP datagram, IP uses the
- For each route in the routing table, IP performs a
bit-wise logical AND between the destination IP address and the netmask. IP
compares the result with the network destination for a match. If they match,
IP marks the route as one that matches the destination IP address.
- From the list of matching routes, IP determines
the route that has the most bits in the netmask. This is the route that
matches the most bits to the destination IP address and is therefore the
most specific route for the IP datagram. This is known as finding the
longest or closest matching route.
- If multiple closest matching routes are found, IP
uses the route with the lowest metric. If multiple closest matching routes
with the lowest metric are found, IP can choose to use any of those routes.