# Router
## What is a Router
A router is a network device that operates at the Network layer of the OSI model. Its primary function is to connect different networks and route packets between them based on their destination IP addresses. While a switch connects devices within the same network using MAC addresses, a router connects separate networks and uses IP addresses to determine where to send packets. Routers are essential devices that make the internet function, directing traffic between the thousands of networks that make up the global internet.
## How a Router Works
Every router maintains a routing table that lists known network destinations and the next hop or interface to use to reach each destination. When a packet arrives at a router, the router examines the destination IP address in the packet header. It then performs a lookup in its routing table to find the best matching entry for that destination address. The best match is the entry with the longest prefix that matches the destination IP address, a process called longest prefix matching. The router then forwards the packet to the next-hop address specified in the matching routing table entry. This process of receiving a packet and forwarding it toward its destination repeats at each router along the path until the packet reaches its destination network.
## Static and Dynamic Routing
Routers can learn routes in two ways. Static routes are manually entered by a network administrator. They do not change automatically and do not adapt to network changes. Static routing is suitable for small, simple networks where the topology rarely changes. Dynamic routing uses routing protocols that allow routers to automatically discover routes and share information about the network topology with each other. When a network link fails, dynamic routing protocols automatically recalculate routes and update the routing tables to route traffic around the failure.
## Network Address Translation
Home routers and many enterprise routers perform Network Address Translation. This allows multiple devices on a private network to share a single public IP address when communicating with the internet. The router maintains a translation table that maps the private IP addresses and port numbers of internal devices to the single public IP address. When a packet from an internal device goes out to the internet, the router replaces the private IP address with its own public IP address. When a response comes back from the internet, the router uses the translation table to determine which internal device should receive the response.
## Default Gateway
The default gateway is the IP address of the router that a device uses to send packets destined for addresses outside its local network. When a device wants to communicate with a device on a different network, it sends the packet to its default gateway router. The router then handles the task of routing the packet toward its final destination.Back to Subject