IP Forwarding: Routing Tables, Longest Prefix Match and Following a Packet
How hosts and routers decide where each IP datagram goes next: what a forwarding table contains, the longest prefix match rule, direct and indirect delivery, why MAC addresses change at every hop while IP addresses don't, and what happens when there is no route.
kvi5hnuCode Sprout team member15 min readOn this page
Forwarding is the job IP does on every datagram: look at its destination address and decide where to send it next. A host does it for packets it sends, and a router does it for millions of packets a second that are passing through. This article explains the forwarding table, the longest prefix match rule that picks one entry from it, and what a packet looks like as it crosses real routers in the lab.
Hosts and routers
Every IP node can forward datagrams it creates itself. The difference between a host and a router is what happens to a datagram that arrives on an interface and isn't addressed to the node:
- A router forwards it toward its destination.
- A host discards it.
On Linux, one setting switches between the two: net.ipv4.ip_forward (and net.ipv6.conf.all.forwarding for IPv6). Any machine with two interfaces and forwarding enabled is a router. That's what a home router is, and what the lab's routers are.
When a datagram arrives, IP does one of three things:
- If the destination is one of the node's own addresses, or a broadcast or multicast address it listens to, it delivers the datagram locally, to the protocol named in the Protocol or Next Header field.
- Otherwise, if forwarding is enabled, it forwards the datagram, as described below.
- Otherwise, it silently drops it.
The forwarding table
IP's decisions come from a forwarding table (often called the routing table). The standards don't fix its format, but each entry needs, at least conceptually:
- Destination and mask, together a prefix such as
203.0.113.0/24. The entry matches any address whose first 24 bits equal those of203.0.113.0. A/0prefix (0.0.0.0/0, ordefault) matches every address. A/32(or/128in IPv6) is a host route for one address. - Next hop: the IP address of the neighbor to send to, which must be directly reachable on one of the node's links. A directly connected network has no next hop: the destination itself is the neighbor.
- Interface: which link to send on. This also determines the source address a host uses for packets it originates (article 28).
Here is the table of the lab host h1. It has one directly connected network and a default route pointing at router ra:
default via 192.0.2.1 dev eth0
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10
And router ra, which connects two networks and has one route learned elsewhere, for the network behind router rb:
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.1
198.51.100.0/24 dev eth1 proto kernel scope link src 198.51.100.1
203.0.113.0/24 via 198.51.100.2 dev eth1
The proto kernel scope link entries are created automatically when an address is configured: assigning 192.0.2.1/24 to eth0 says "the whole /24 is reachable directly on eth0". Other routes are added by hand (ip route add), by DHCP or Router Advertisements (articles 29–32), or by a routing protocol such as OSPF or IS-IS (used inside one organization's network) or BGP (used between networks across the Internet). Routing protocols aren't covered in this course. They exchange reachability information between routers and install the results in each router's table.
Longest prefix match
Often several entries match a destination. A default route matches everything, and a network can be covered by both a broad route and a more specific one. The rule is simple: use the matching entry with the longest prefix, because it's the most specific. In steps, for destination address D:
- Find every entry where
D AND maskequals the entry's destination. - Among them, pick the one with the longest mask (the most 1 bits).
- Send the datagram to that entry's next hop, or directly to D if the entry is a connected network, through the entry's interface.
- If nothing matches (there's no default route), drop the datagram and report an error: an error to the sending application on a host, or an ICMP Destination Unreachable message from a router.
A small worked example of step 1, looking only at the last byte (the first three bytes, 203.0.113, match in every case). Does 203.0.113.150 match 203.0.113.128/25? The /25 mask ends in 10000000, and 150 is 10010110, so 150 AND mask is 10000000 = 128, which equals the entry's last byte: yes. For 203.0.113.10, 10 is 00001010, AND 10000000 gives 0, not 128: no.
To see the rule at work, the lab added three overlapping routes to ra: a /25 inside its existing /24, a host route /32 inside that, and a default route. Each points at a different next hop on the 192.0.2.0/24 link (.20, .30 and .40, addresses that exist only for this lookup), so you can tell which route was chosen:
default via 192.0.2.40 dev eth0
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.1
198.51.100.0/24 dev eth1 proto kernel scope link src 198.51.100.1
203.0.113.0/24 via 198.51.100.2 dev eth1
203.0.113.128/25 via 192.0.2.20 dev eth0
203.0.113.200 via 192.0.2.30 dev eth0
ip route get asks the kernel which route it would use for a destination. Each line shows the next hop (via), the outgoing interface, and the source address the node would use. A line without via means direct delivery. (uid 0 is just the user who asked, here root.) The grid after the output shows which entries matched each destination and which one won:
203.0.113.10 via 198.51.100.2 dev eth1 src 198.51.100.1 uid 0
203.0.113.150 via 192.0.2.20 dev eth0 src 192.0.2.1 uid 0
203.0.113.200 via 192.0.2.30 dev eth0 src 192.0.2.1 uid 0
198.18.0.1 via 192.0.2.40 dev eth0 src 192.0.2.1 uid 0
198.51.100.2 dev eth1 src 198.51.100.1 uid 0

Longest match is what makes aggregation (article 9) work. A provider can advertise one short prefix for all its customers, while inside its own network more specific routes send each customer's traffic to the right place. It also allows exceptions: a single /32 can divert one address without touching anything else.
Real routers hold about 1.1 million IPv4 prefixes and about 270,000 IPv6 prefixes for the global Internet (public BGP table reports, late 2026), and do this lookup for every packet. They use special data structures (tries) and hardware such as TCAM (ternary content-addressable memory, chips that compare an address against every entry at once) to do it in nanoseconds. The rule itself is still exactly the one above.
Direct and indirect delivery
The result of a lookup is one of two kinds of delivery:
- Direct delivery. The destination is on a connected network, so the node sends the datagram straight to it on that link.
- Indirect delivery. The destination is somewhere else, so the node sends the datagram to a next-hop router, which repeats the whole process.
Either way, the node needs the link-layer address of whoever is next: the destination itself, or the next-hop router. On Ethernet and Wi-Fi it uses ARP for IPv4 (article 21) or Neighbor Discovery for IPv6 (article 42), and caches the answers. The first line below is h1's cache, which holds only its router ra. The rest is ra's cache, with h1 on one side, rb on the other, and h1's IPv6 link-local address. The last word of each line is the neighbor state from article 21:
192.0.2.1 lladdr 02:00:00:00:01:01 REACHABLE
192.0.2.10 dev eth0 lladdr 02:00:00:00:01:10 DELAY
198.51.100.2 dev eth1 lladdr 02:00:00:00:02:02 REACHABLE
fe80::ff:fe00:110 dev eth0 lladdr 02:00:00:00:01:10 STALE
Following one packet
Here's a single ping from h1 (192.0.2.10) to h2 (203.0.113.10), captured on each of the three links it crossed. The figure after the table draws the same three hops:
Link Ethernet src Ethernet dst IP src IP dst TTL
1: h1 -> ra 02:00:00:00:01:10 02:00:00:00:01:01 192.0.2.10 203.0.113.10 64
2: ra -> rb 02:00:00:00:02:01 02:00:00:00:02:02 192.0.2.10 203.0.113.10 63
3: rb -> h2 02:00:00:00:03:01 02:00:00:00:03:10 192.0.2.10 203.0.113.10 62

Three facts from this capture explain most of how the Internet moves packets:
- The IP source and destination never change. Without NAT (article 35), the datagram is addressed end to end from the moment it's created.
- The link-layer addresses change on every link. Each Ethernet header names only the two interfaces at the ends of that one link. A router removes the incoming frame, makes its forwarding decision, and builds a completely new frame for the outgoing link. On a link without addresses, such as a point-to-point PPP link, there's no link-layer address at all.
- Each router knows only the next hop.
h1knows only "send it tora".raknows only "send it torb". No node knows the whole path. That keeps routers simple, but it means the routing protocols must keep every router's table consistent, or packets loop until their TTL runs out.
This hop-by-hop model is also why tools that run at the link layer, such as switches, don't appear in traceroute: they forward frames without touching the IP header.
When there is no route
If a host has no matching route, the error happens locally, before any packet is sent. If a router has no matching route, it drops the packet and sends an ICMP error back to the source. Both cases, from the lab:
ping: connect: Network is unreachable
From 192.0.2.1 icmp_seq=1 Destination Net Unreachable
The first line came from h1 itself after its default route was removed: the connect() call failed with ENETUNREACH. The second came from router ra after its route to 203.0.113.0/24 was removed: an ICMP Destination Unreachable, code 0 (network unreachable). Article 40 covers the ICMP error types.
And if forwarding is turned off on the router, it becomes a host and silently drops transit packets, with no ICMP message at all:
2 packets transmitted, 0 received, 100% packet loss, time 1043ms
IpInAddrErrors 2 0.0
IpForwDatagrams 4 0.0
IpExtInNoRoutes 1 0.0
The nstat lines give a counter name, its value and a rate. IpForwDatagrams (4) counts the packets the box forwarded earlier, while forwarding was on, and IpExtInNoRoutes (1) is the lookup that failed in the previous test. The IpInAddrErrors counter counts datagrams that arrived for an address the node doesn't own and that it wasn't allowed to forward. When you're debugging "packets vanish at this box", nstat (or netstat -s) counters like these are often the fastest clue.
Beyond the simple table
Real systems add a few refinements to the basic model:
- Equal-cost multipath (ECMP). A route can have several next hops, and the router spreads traffic across them, normally by hashing each packet's addresses and ports (or IPv6 Flow Label) so that one flow always uses one path and its packets stay in order:
203.0.113.0/24
nexthop via 198.51.100.2 dev eth1 weight 1
nexthop via 198.51.100.3 dev eth1 weight 1
- Policy routing. Linux can keep several tables and choose one by rules other than the destination, for example by source address, firewall mark or incoming interface (
ip rule). VPN software and multihomed servers use this. - MPLS. Inside many provider networks, the first router assigns a label and later routers forward by label instead of by IP lookup (the virtual circuits of article 1). The IP datagram travels unchanged inside.
- RIB and FIB. Routers keep everything their routing protocols learned in a Routing Information Base, and install only the best routes into the Forwarding Information Base that the hardware uses for lookups.
Common questions
What is the difference between a routing table and a forwarding table?
The terms are often used interchangeably. Strictly, the routing table (RIB) holds all routes learned from all sources, possibly several per prefix, and the forwarding table (FIB) holds just the chosen best route for each prefix, in a form optimized for fast lookup. On a Linux host they're effectively the same thing, shown by ip route.
Why is the default route 0.0.0.0/0, and why doesn't it always win, since it matches everything?
A /0 prefix has a mask of all zeros, so every address ANDed with it gives 0.0.0.0, and it matches. But it's the shortest possible prefix, so any other matching route is more specific and beats it. The default is used only when nothing else matches.
Does a router look at the source address when forwarding?
Normally only the destination is used to choose the route. The source matters for policy routing, for firewall rules, and for reverse path filtering: many routers check that a packet's source address would be routed back out the interface it arrived on, and drop it if not. That defends against spoofing (article 5). On Linux this is the rp_filter setting.
What if two routes have exactly the same prefix?
Longest match can't separate them, so a tie-breaker decides. On Linux, each route has a metric (ip route add ... metric 100), and the lowest metric wins. That's how a laptop with both Ethernet and Wi-Fi up has two default routes and prefers the wired one, which its network manager gave a lower metric. Routers first compare where each route came from (static, OSPF, BGP and so on, ranked by an "administrative distance" or "preference"), then the routing protocol's own metric. Routes that tie on everything can be installed together as an ECMP route, described above.
Why does my packet's TTL go down by one per router but not per switch?
Switches forward Ethernet frames, not IP datagrams. They don't look at or change the IP header, so they're invisible at the IP layer. Only routers, which make IP forwarding decisions, decrement TTL.
What does "next hop must be on a connected network" mean?
The next-hop address must be reachable directly on one of the node's links, because the node has to learn its MAC address with ARP or Neighbor Discovery and put it in a frame. A route via an address that's several hops away can't be used directly. Linux rejects such a route with "Nexthop has invalid gateway" unless you specify onlink.
Do all packets of one TCP connection follow the same path?
Usually yes. With ECMP, routers hash the flow's addresses and ports, so one connection stays on one path. But when routes change, or in networks that spread individual packets, a connection's packets can take different paths and arrive out of order. TCP handles that, but a lot of reordering hurts performance.
Summary
- Hosts and routers both forward their own datagrams. Only routers forward datagrams addressed to others, and on Linux
ip_forwardswitches a machine between the two roles. - A forwarding table entry is a prefix (destination and mask), a next hop and an interface. Connected networks appear automatically when addresses are configured.
- Longest prefix match: of all matching entries, the most specific wins, and the default route
/0is used only when nothing else matches. - Direct delivery sends straight to the destination on a shared link. Indirect delivery sends to a next-hop router. Either way, the link-layer address comes from ARP or Neighbor Discovery.
- Across a path, IP addresses stay the same while Ethernet addresses change at every hop, and each router decrements TTL. Every node knows only the next hop.
- No route on a host gives a local "Network is unreachable" error. No route on a router gives an ICMP Destination Unreachable. A box with forwarding disabled drops transit packets silently.
Practice questions
1. A router has these routes: 0.0.0.0/0 via A, 203.0.113.0/24 via B, 203.0.113.128/25 via C, 203.0.113.192/26 via D. Which next hop is used for 203.0.113.200, 203.0.113.150, 203.0.113.20 and 192.0.2.1?
Answer
203.0.113.200 → D (it's in the /26, which covers .192 to .255, and also in the /25 and /24, but the /26 is longest). 203.0.113.150 → C (the /25 covers .128 to .255, but .150 is below .192). 203.0.113.20 → B (only the /24 and the default match). 192.0.2.1 → A (only the default matches).
2. A capture on the second link of a path shows an IP datagram from 192.0.2.10 to 203.0.113.10. What are its Ethernet source and destination addresses?
Answer
The MAC address of the router interface that sent the frame on that link (the first router's outgoing interface) and the MAC address of the next hop on that link (the second router's incoming interface, or the destination host if it's on that link). They're never the MAC addresses of 192.0.2.10 or, unless it's on that link, of 203.0.113.10.
3. You remove the default route from a laptop and run ping 198.51.100.1, which is not on any of its connected networks. Does any packet leave the laptop?
Answer
No. The lookup finds no matching route, so the error ("Network is unreachable", ENETUNREACH) is returned to ping immediately, before anything is sent.
4. A Linux machine with two interfaces receives a packet for an address on its other interface's network, but nothing comes out the other side. nstat shows IpInAddrErrors increasing. What's the likely cause?
Answer
IP forwarding is disabled (net.ipv4.ip_forward = 0), so the machine acts as a host and drops datagrams not addressed to itself. Enable forwarding to make it a router (and check firewall rules too).
5. Why do VPN clients often add two /1 routes, one for the lower half of the IPv4 address space (0.0.0.0/1) and one for the upper half, instead of replacing the default route?
Answer
Together the two /1 routes cover the whole IPv4 address space, and each is more specific than the /0 default, so longest prefix match sends all traffic through the VPN while the original default route stays in place. When the VPN disconnects and removes its routes, the old default route takes over again without having to be restored.
6. How does a router avoid reordering the packets of one TCP connection when it has two equal-cost paths?
Answer
It chooses a path per flow, not per packet: it hashes fields that are constant for the connection, such as the source and destination addresses, the protocol and the ports (or the IPv6 Flow Label), and always sends that flow on the path the hash selects.
Previous: IPv4 Options and IPv6 Extension Headers: Hop-by-Hop, Routing and Fragment Headers

More in TCP/IP Course
Quiz: TCP/IP Delicate Details
Twenty-five questions on the details that catch out experienced engineers: sequence numbers for SYN and FIN, TIME_WAIT versus tcp_fin_timeout, Karn's algorithm, socket buffer doubling, even and odd ephemeral ports, IPv6 checksums and fragmentation, negative DNS caching, and capture filter traps.
Quiz: TCP/IP Interview Questions
Thirty-three networking questions of the kind asked in developer, SRE and network engineering interviews: what happens when you load a URL, TCP versus UDP, handshakes, closing and TIME_WAIT, subnetting, NAT, DNS, MTU problems, congestion, TLS and QUIC, and debugging slow or failing connections.
Quiz: TCP/IP Course Final Exam (All Parts)
The final exam for the TCP/IP course: thirty questions across all fourteen parts, from packets and addressing through Ethernet, ARP, IP, DHCP, NAT, ICMP, UDP, DNS, TCP connections, reliability, congestion control, security, QUIC and troubleshooting.
Quiz: Modern Transports and Troubleshooting (TCP/IP Part 14)
Review modern transports and troubleshooting: QUIC packets, handshakes, 0-RTT, streams and connection migration, HTTP/3, Multipath TCP, SCTP multihoming, and a layered method for diagnosing real network faults.
Discussion
Sign in to ask a question or share what you learned.