Learn TCP/IP Networking Routing and Gateways
Lesson 11 of 12

Routing and Gateways

Routing and Gateways — How Traffic Moves Between Networks

Every time you visit a website, stream a video, or send an email, your data crosses multiple networks before it reaches its destination. None of that works without routing. Routing is the mechanism that decides where packets go when they leave your local network — which paths they take, which devices forward them, and how they eventually reach the right machine on the other side of the world.

This file explains how routing works from the ground up: how your device decides whether to send a packet directly or hand it to a gateway, how routers use routing tables to make forwarding decisions, how dynamic routing protocols keep the internet functioning, and how Network Address Translation (NAT — defined below) lets millions of home networks share a limited pool of public addresses. It also explains how attackers exploit routing — from BGP (Border Gateway Protocol) hijacking to forged ICMP (Internet Control Message Protocol) redirect messages — and why routing knowledge is foundational to understanding firewall policy and network defense.


What Routing Is

Routing is the process of selecting paths for network traffic to travel from a source to a destination across one or more networks. A router is a dedicated device — or a computer configured to act as one — that connects multiple networks and forwards packets between them based on destination IP (Internet Protocol) addresses.

Without routing, devices on different networks would be completely isolated. They could exchange data only with other devices on the same local segment. The internet, as you know it, is a collection of hundreds of thousands of individual networks that routing makes navigable.

When a packet arrives at a router, the router examines the destination IP address in the packet header and consults its routing table — a set of rules — to determine where to send the packet next. This process repeats at each router along the path until the packet reaches its destination network, at which point the final router delivers it to the target device.

The sequence of routers a packet passes through is called the path or the hop path. Each router along the way is one hop. The number of hops a packet traverses depends on the size and complexity of the networks involved. A packet crossing the internet may pass through a dozen or more routers.


The Default Gateway

The default gateway is the IP (Internet Protocol) address of the router that a device sends traffic to when the destination is not on the local network. It is, in practical terms, the "way out" of the local network — the door your packets walk through when they need to go somewhere your device cannot reach directly.

Every device that needs to communicate beyond its local network segment must be configured with a default gateway. On home and office networks, this address is typically assigned automatically by DHCP (Dynamic Host Configuration Protocol) — the same process that gives your device its IP address.

How Your Device Decides Where to Send a Packet

When your device prepares to send a packet, it goes through a decision process before transmitting anything:

Step 1 — Is the destination on my local network?

Your device compares the destination IP address with its own IP address and subnet mask. The subnet mask defines the boundary of your local network. If the destination falls within the same network range, the destination device is directly reachable on the local segment.

Step 2a — If yes: send directly

Your device uses ARP (Address Resolution Protocol) to discover the MAC (Media Access Control) address of the destination device, then transmits the packet directly to that device. No router involvement is required.

Step 2b — If no: send to the default gateway

Your device uses ARP to discover the MAC address of the default gateway router. It sends the packet to the router's MAC address. The router then takes responsibility for forwarding the packet toward the destination — possibly through several more routers before reaching its target network.

This distinction matters: even when sending to a remote destination, your device only physically transmits to the next-hop address on the local segment (the gateway). Routing is an end-to-end concept built from a sequence of local decisions, one hop at a time.

Finding Your Default Gateway

You can view your default gateway with standard operating system commands:

ipconfig              # Windows — look for "Default Gateway" under your network adapter
ip route show         # Linux — shows the routing table; the default route lists the gateway
netstat -rn           # Linux and macOS — shows the routing table in numeric format
route print           # Windows — shows the full routing table

On Windows, ipconfig output looks like this:

Ethernet adapter Local Area Connection:
   IPv4 Address. . . . . . . . . . . : 192.168.1.50
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1

Here, 192.168.1.1 is the gateway. Any packet destined for an address outside the 192.168.1.0/24 range goes to 192.168.1.1 first.


Routing Tables

Every device that handles IP traffic — not just routers, but also your laptop, desktop, and server — maintains a routing table. A routing table is a set of rules that determine where to send a packet based on its destination IP address.

Routers have large, complex routing tables with hundreds of thousands of entries. Your workstation has a small routing table with just a handful of rules, but the logic is identical.

What Each Routing Table Entry Contains

Each row in a routing table includes the following fields:

Destination network: The range of IP addresses this rule covers. Written in CIDR (Classless Inter-Domain Routing) notation (for example, 10.1.2.0/24) or as an address plus a subnet mask.

Subnet mask / prefix length: Defines the scope of the destination range. A /24 prefix covers 256 addresses; a /32 covers exactly one address.

Next hop / gateway: Where to send packets matching this rule. This is either the IP address of the next router in the path, or an indicator that the destination is directly connected (meaning the device can reach it without going through another router).

Interface: Which physical or virtual network interface to use when forwarding the packet (for example, eth0 on Linux, or "Local Area Connection" on Windows).

Metric: A cost value for this route. Lower metrics are preferred. When two routes exist to the same destination, the router uses the one with the lower metric. Metrics can represent hop count, link speed, reliability, or a combination.

Viewing the Routing Table

route print             # Windows — full routing table including IPv4 and IPv6
ip route show           # Linux — concise routing table view
netstat -rn             # Linux and macOS — routing table in numeric form (no DNS resolution)

Example Linux Routing Table

Destination     Gateway         Genmask         Flags Metric Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    100    eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     100    eth0

Reading this table:

The first row — destination 0.0.0.0 with genmask 0.0.0.0 — is the default route. It matches any destination address not matched by a more specific rule. Packets going to the internet go here. The gateway is 192.168.1.1, meaning those packets are forwarded to that router. The flag "UG" means the route is Up and uses a Gateway. The interface is eth0.

The second row — destination 192.168.1.0 with genmask 255.255.255.0 — is the directly connected local network rule. Packets to any address in the 192.168.1.0/24 range are sent directly through eth0 without going through a gateway (the gateway column shows 0.0.0.0, indicating direct delivery). The flag "U" means the route is Up.

In CIDR notation, these are written 0.0.0.0/0 (the default route) and 192.168.1.0/24 (the local network).


Longest Prefix Match

When a destination IP address matches more than one entry in the routing table, the router does not pick arbitrarily. It uses longest prefix match: it selects the most specific matching route — the one with the most network bits in the prefix (the highest prefix length number).

Example: A router has these entries:

10.0.0.0/8       via 192.168.1.1
10.1.2.0/24      via 10.5.0.1
0.0.0.0/0        via 203.0.113.254

A packet arrives destined for 10.1.2.50. This address matches all three rules:

  • 10.0.0.0/8 — yes, 10.1.2.50 falls within this /8 range
  • 10.1.2.0/24 — yes, 10.1.2.50 falls within this /24 range
  • 0.0.0.0/0 — yes, the default route matches everything

The router selects 10.1.2.0/24 because /24 is the longest prefix (most specific match). The packet goes to 10.5.0.1.

This principle is why default routes work: 0.0.0.0/0 is the least specific possible route. Any more specific route beats it. The default route only wins if no more specific route exists.

Longest prefix match is a fundamental concept for understanding how routers make decisions, how traffic engineering works, and how attackers can manipulate routing by injecting more specific routes to divert traffic through attacker-controlled infrastructure.


Static Routing vs. Dynamic Routing

Routes can be configured in two fundamentally different ways: statically (manually configured by a person) or dynamically (learned automatically through routing protocols).

Static Routing

In static routing, a network administrator manually adds routes to each router's routing table. The routes stay in place until an administrator changes them.

Characteristics of static routing:

  • Simple and predictable — the router does exactly what you configured
  • No protocol overhead — static routes consume no bandwidth for routing updates
  • Does not adapt automatically — if a link fails, traffic does not reroute until an administrator intervenes
  • Appropriate for small, simple networks where the topology rarely changes
  • Appropriate for specific paths that must always be forced through a particular device (for example, all internet traffic through a specific security appliance)

When static routing breaks: If the sole uplink to the internet goes down, a statically configured router cannot find an alternative path. Traffic stops until the link is restored or an administrator adds a new route. In large networks with many redundant paths, managing static routes manually becomes impractical.

Dynamic Routing

In dynamic routing, routers use routing protocols to exchange information with each other about the networks they can reach. They build their routing tables automatically based on this exchanged information.

Characteristics of dynamic routing:

  • Adapts automatically — if a link fails, routers detect the change and reroute traffic through alternative paths
  • Scales to large and complex networks that would be impossible to manage statically
  • Introduces protocol overhead — routers exchange update messages, which consume bandwidth and CPU
  • Requires understanding and configuration of the routing protocol in use

The process of routers exchanging information and updating their routing tables after a change is called convergence. Faster convergence means less disruption when the network topology changes.

Common Routing Protocols

RIP — Routing Information Protocol: RIP is a simple distance-vector protocol. Each router broadcasts its routing table to its neighbors every 30 seconds. Routes are measured in hop count — the number of routers between source and destination. RIP has a maximum hop count of 15; any destination requiring 16 or more hops is considered unreachable. This limits RIP to small networks. RIP is slow to converge after topology changes. It is rarely used in modern networks but still appears in older deployments and on small embedded devices. Defined in RFC (Request for Comments) 2453.

OSPF — Open Shortest Path First: OSPF is a link-state protocol. Instead of sharing their routing tables, OSPF routers share information about the state of their individual links — which interfaces are up, their speeds, and their costs. Each router builds a complete map of the entire network topology and then independently calculates the shortest path to every destination using Dijkstra's algorithm. OSPF converges quickly after failures, scales to large networks, and is the dominant interior routing protocol in enterprise environments. Defined in RFC 2328.

BGP — Border Gateway Protocol: BGP is the routing protocol of the internet itself. While RIP and OSPF are used inside individual organizations, BGP is used between organizations — specifically between autonomous systems. An autonomous system (AS) is a large network or group of networks under a single administrative authority: an internet service provider (ISP), a university, a cloud provider, or a large corporation. Each AS has a globally unique AS number assigned by IANA. BGP routers at the borders of these autonomous systems exchange reachability information — which IP address ranges each AS can deliver traffic to. When you send a packet to a server in another country, BGP is what allows routers across the globe to know which AS to route toward and how to reach it. BGP is what makes the internet a single interconnected network rather than isolated islands. Defined in RFC 4271.

EIGRP — Enhanced Interior Gateway Routing Protocol: EIGRP is a Cisco-proprietary advanced distance-vector protocol. It combines elements of distance-vector and link-state approaches, converges faster than RIP, and is used in enterprise networks built on Cisco equipment. Because it is proprietary, it is less common in mixed-vendor environments.


NAT — Network Address Translation

NAT (Network Address Translation) is a technique that allows devices using private IP addresses to communicate with the internet by translating those private addresses to a public address at the router.

Why NAT Exists

IPv4 (IP version 4) addresses are 32 bits long, which allows approximately 4.3 billion unique addresses. The internet has billions of devices — far more than 4.3 billion when you count phones, computers, servers, and embedded devices. There are not enough public IPv4 addresses to give every device its own globally unique address.

To solve this, RFC (Request for Comments) 1918 designated three address ranges as private address space — addresses that can be used freely within private networks but are not routed on the public internet:

10.0.0.0    – 10.255.255.255    (10.0.0.0/8)
172.16.0.0  – 172.31.255.255    (172.16.0.0/12)
192.168.0.0 – 192.168.255.255   (192.168.0.0/16)

Millions of home and office networks use 192.168.x.x addresses. These addresses are identical across millions of different private networks — they are only meaningful within the network that uses them. NAT is the mechanism that allows devices with these non-unique private addresses to reach the public internet, which does require unique addresses.

How NAT Works — Step by Step

Here is what happens when a device on a private network accesses a website:

  1. Your device at private address 192.168.1.100 sends a packet to the web server at 8.8.8.8. The source IP is 192.168.1.100, the source port is 52800 (an ephemeral port assigned by your operating system), the destination IP is 8.8.8.8, and the destination port is 443 (HTTPS — Hypertext Transfer Protocol Secure).

  2. The packet reaches the NAT-enabled router. The router records a mapping in its NAT table: internal address 192.168.1.100:52800 corresponds to external address 203.0.113.1:40001. The router rewrites the packet's source IP from 192.168.1.100 to 203.0.113.1 (its own public IP address) and the source port from 52800 to 40001. The packet now has a legitimate public source address.

  3. The packet travels the internet with source IP 203.0.113.1:40001 and reaches 8.8.8.8.

  4. The server at 8.8.8.8 sends its response to 203.0.113.1:40001 — the only address it knows about.

  5. The router receives the response. It looks up port 40001 in its NAT table, finds the mapping, rewrites the destination IP from 203.0.113.1 to 192.168.1.100 and the destination port from 40001 to 52800, and forwards the packet to your device.

Your device receives the response as if it had communicated directly with 8.8.8.8. The NAT translation is invisible to both your device and the remote server.

PAT — Port Address Translation

PAT (Port Address Translation), also called NAPT (Network Address Port Translation), is the specific form of NAT that virtually every home router uses. PAT allows many internal devices to share a single public IP address simultaneously by using different port numbers to distinguish between their sessions.

Without PAT, a single public IP could only have one active NAT session at a time. With PAT, the router assigns a different external port number to each internal session, allowing hundreds or thousands of concurrent connections through one public IP.

Types of NAT

SNAT — Source NAT: Translates the source IP address of outgoing packets. This is the standard form used for outbound traffic from private networks to the internet. The router replaces private source addresses with its public address.

DNAT — Destination NAT: Translates the destination IP address of incoming packets. Used to direct inbound traffic to a specific internal server. For example, incoming traffic on port 443 of the router's public IP might be translated to port 443 of an internal web server at 192.168.1.200.

Port forwarding: A specific implementation of DNAT. An administrator configures the router to forward inbound traffic on a specific port to a specific internal host. This is how home users make a web server, game server, or security camera accessible from the internet.

NAT and Security

NAT provides a degree of incidental isolation: unsolicited inbound connections from the internet have no pre-existing NAT table entry to match and are therefore dropped by the router. This prevents an attacker on the internet from directly initiating a connection to a device behind NAT without the device having first reached out.

However, it is important to understand what NAT is and is not:

NAT was designed for address conservation, not security. Its isolation behavior is a side effect of how translation tables work, not an intentional security feature.

A dedicated stateful firewall is the actual security control. A stateful firewall explicitly tracks connection state and blocks unsolicited inbound traffic based on security policy. NAT's incidental blocking behavior can be bypassed in various ways — for example, through techniques like NAT traversal, which VPN (Virtual Private Network) and peer-to-peer applications use deliberately.

Never rely on NAT as your primary defense. Use a proper firewall.


Security Relevance of Routing

BGP Hijacking

BGP (Border Gateway Protocol) has almost no built-in security. Routers trust that their peers are announcing legitimate routes. An attacker — whether a rogue network operator, a misconfigured router, or a compromised BGP session — can announce false routes, claiming to be the shortest path to IP address ranges they do not actually control. Traffic destined for those ranges gets routed to the attacker instead of the legitimate destination.

Real-world example: In April 2018, attackers announced false BGP routes to divert traffic bound for Amazon Route 53's DNS (Domain Name System) service. For about two hours, DNS queries for MyEtherWallet.com — a popular cryptocurrency wallet service — were answered by attacker-controlled servers. The attacker's servers returned fraudulent responses pointing users to a fake version of the site, where credentials were harvested and cryptocurrency was stolen. The attack exploited BGP's inherent trust model.

Defense: RPKI (Resource Public Key Infrastructure) provides cryptographic route origin validation. An RPKI-signed Route Origin Authorization (ROA) records which AS is authorized to announce a given IP prefix, allowing routers to reject announcements from unauthorized sources. Adoption of RPKI has grown significantly but is not yet universal.

Route Injection

An attacker with access to a router — through a compromised administrative account, a stolen credential, or physical access — can inject false static routes. These routes divert traffic through an attacker-controlled machine, where it can be intercepted, read, copied, or modified before being forwarded to the legitimate destination. This is a form of man-in-the-middle (MITM) attack at the routing layer.

Route injection on internal networks is one reason why router management interfaces should be protected with strong authentication, accessible only from trusted management networks, and monitored for unauthorized configuration changes.

ICMP Redirects

ICMP (Internet Control Message Protocol) Type 5 is the Redirect message. Routers use it to tell a host that a better gateway exists for a particular destination. For example, if a host sends a packet to the router, and the router knows the host could reach the destination more efficiently through a different router on the same segment, the router forwards the packet and sends an ICMP Redirect back to the host, telling it to use the better gateway in the future.

The problem: any machine on the local network can forge an ICMP Redirect message. An attacker can send a crafted ICMP Redirect to a host telling it to use the attacker's machine as its gateway for specific destinations. If the host honors the redirect, traffic is silently diverted through the attacker for interception.

Defense: Most modern operating systems ignore ICMP Redirect messages by default because of this risk. On Linux, this is controlled by the kernel parameter net.ipv4.conf.all.accept_redirects. You should verify this is set to 0 (disabled) on any machine that handles sensitive traffic.

Firewall Rules and Routing Awareness

Understanding routing is a prerequisite to writing effective firewall rules. A firewall rule allows or blocks traffic based on source IP, destination IP, port, and protocol. But which rules apply to which traffic depends on how traffic flows through the network and which interfaces it crosses.

Consider a simple example: you want to block external access to an internal database server. If you do not understand how traffic is routed to the database — which interface it enters, which router it passes through, which subnet it sits on — you cannot write a rule that reliably blocks it. A rule on the wrong interface or in the wrong rule chain does nothing.

Network segmentation — dividing your network into isolated zones with controlled routing between them — is itself a routing concept. The security principle of least privilege applied to networks means traffic should only be able to route where it is explicitly permitted to go.


The Bottom Line

Routing is the mechanism that connects the world's networks into a single internet. Every packet you send to a remote destination relies on routing decisions made at each hop. Your device's routing table determines whether a packet goes directly to a local destination or to the default gateway for forwarding. Routers use longest prefix match to select the most specific applicable route. Static routing is simple and predictable but does not adapt to failures. Dynamic routing protocols — RIP, OSPF, BGP — enable automatic route learning and adaptation at scales ranging from a small office to the global internet. NAT allows private IP address spaces to share public addresses, providing incidental isolation as a side effect of address translation — but not a substitute for a stateful firewall. BGP hijacking, route injection, and ICMP redirect attacks all exploit the trust assumptions built into routing infrastructure, making routing knowledge essential for anyone working in network defense.


Check Your Understanding

  1. Your device has the IP address 192.168.10.50 with a subnet mask of 255.255.255.0. You send a packet to 192.168.20.100. Does your device send the packet directly to the destination, or does it forward it to the default gateway? Explain the decision process your device uses to reach this conclusion.

  2. A router's routing table has three entries: 10.0.0.0/8 via Router A, 10.5.0.0/16 via Router B, and 0.0.0.0/0 via Router C. A packet arrives destined for 10.5.7.200. Which entry does the router use, and why?


Something to Think About

  1. BGP has almost no authentication — routers largely trust each other's announcements. The internet has functioned this way for decades, and RPKI adoption is still incomplete. Given that BGP hijacking can redirect traffic for millions of users at once, what factors do you think have slowed the adoption of cryptographic defenses like RPKI? What would it take to make secure routing universal?

  2. NAT is widely described as providing "security through obscurity" — its isolation effect is a side effect, not a design goal. But billions of devices rely on it as their primary barrier to direct internet exposure. If IPv6 (IP version 6) adoption were complete and every device had a globally unique public address with no NAT, what changes would need to happen to firewall and host security practices to maintain the level of protection that NAT's side effects currently provide?


References

  1. Official Specification. RFC 4271 — "A Border Gateway Protocol 4 (BGP-4)". IETF. — The BGP-4 specification; the inter-domain routing protocol that connects autonomous systems and makes the global internet function as a single network.

  2. Official Specification. RFC 2328 — "OSPF Version 2". IETF. — The OSPF (Open Shortest Path First) specification for enterprise link-state routing; widely deployed in corporate and campus networks.

  3. Official Specification. RFC 2453 — "RIP Version 2". IETF. — The RIP (Routing Information Protocol) version 2 specification; documents the simple distance-vector protocol used in small networks.

  4. Official Specification. RFC 2663 — "IP Network Address Translator (NAT) Terminology and Considerations". IETF. — NAT terminology and architectural considerations; foundational reference for understanding how NAT works, its variants, and its limitations.

  5. Official Specification. RFC 1918 — "Address Allocation for Private Internets". IETF. — Defines the private IP address ranges (10.x.x.x, 172.16.x.x, 192.168.x.x) used in conjunction with NAT in virtually every home and office network.

  6. Real-World Incident. CISA — "Advisory AA23-144A: Volt Typhoon Targets U.S. Critical Infrastructure". CISA, 2023. — Documents advanced persistent threat activity using internal routing knowledge for lateral movement; illustrates why routing understanding matters for both attackers and defenders.

  7. Real-World Incident. Cloudflare Blog — "BGP leak causing Internet outages". Cloudflare. — Documents a BGP routing incident affecting global internet traffic, illustrating BGP's critical importance and its vulnerability to misconfiguration and attack.

  8. Security Reference. NIST SP 800-54 — "Border Gateway Protocol Security". National Institute of Standards and Technology. — NIST guidance on BGP security threats and countermeasures, including RPKI and route filtering best practices.