route ‐ #networking - five4nets/Linux-Knowledgebase GitHub Wiki
Linux Route Command Tutorial
The route
command in Linux is used to display and manipulate the IP routing table. It allows users to view, add, delete, or modify routes in the kernel routing table, which determines how network packets are forwarded. This tutorial explains the route
command, its syntax, and provides practical examples.
Table of Contents
Overview
The route
command is part of the net-tools
package in Linux and is used to manage the routing table, which dictates how network traffic is directed between hosts, networks, or gateways. While newer tools like ip route
(from the iproute2
package) are often recommended for modern systems, route
remains widely used for its simplicity.
Note: You may need root privileges (sudo
) to modify routes.
Syntax
route [options] [command]
Commands
add
: Adds a new route to the routing table.del
: Deletes an existing route from the routing table.- No command: Displays the current routing table.
Common Options
-n
: Displays numerical IP addresses instead of resolving hostnames.-v
: Verbose mode, provides additional details.--help
: Shows help information for the command.
Examples
Displaying the Routing Table
To view the current routing table, run:
route -n
Output Example:
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
Explanation:
Destination
: Target network or host.Gateway
: The IP address of the next hop (gateway) for the route.Genmask
: Subnet mask for the destination.Flags
: Indicators likeU
(route is up),G
(uses gateway).Iface
: Network interface used (e.g.,eth0
).
Adding a Route
To add a route for a specific network (e.g., 10.0.0.0/24
) through a gateway (192.168.1.1
):
sudo route add -net 10.0.0.0 netmask 255.255.255.0 gw 192.168.1.1
Explanation:
-net
: Specifies the destination is a network.gw
: Specifies the gateway IP address.
Deleting a Route
To delete the route added above:
sudo route del -net 10.0.0.0 netmask 255.255.255.0
Explanation:
del
: Removes the specified route.- Ensure the parameters match the route you want to delete.
Adding a Default Gateway
To set a default gateway for all traffic not matching other routes:
sudo route add default gw 192.168.1.1
Explanation:
default
: Refers to the default route (0.0.0.0/0
).- This directs all non-local traffic to the specified gateway.
Modifying an Existing Route
To replace an existing default gateway with a new one:
sudo route del default
sudo route add default gw 192.168.2.1
Explanation:
- First, delete the existing default route.
- Then, add the new default gateway.