10+ ip route command examples in Linux [Cheat Sheet]
In Linux, ip command is used to show or manipulate routing, devices, policy routing and tunnels. ip route is a part of ip command. It helps to manage the route entries in the kernel routing tables that keep information about paths to other networked nodes. The routes can be set for different IP addresses (destination). You can use ip route command to add, delete, change, and list the routes.
Types of route
Following are the different types of routes.
- unicast: It describes real paths to the destinations covered by the route prefix.
- unreachable: Unreachable destinations. The packets are discarded and the ICMP message host unreachable is generated.
- blackhole: Unreachable destinations. The packets are discarded silently.
- prohibi: Unreachable destinations. The packets are discarded and the ICMP message communication administratively prohibited is generated.
- local: The destinations are assigned to this host.
- broadcast: The destinations are broadcast addresses. The packets are sent as link broadcasts.
- throw: The packets are dropped and the ICMP message net unreachable is generated.
- nat: A special nat route. The destinations covered by the prefix are considered dummy (or external) addresses and require translation to real (or internal) ones before forwarding.
- anycast: The destinations are anycast addresses assigned to this host. They are not implemented.
- multicast: A special type for multicast routing. It is not present in normal routing tables.
Syntax for ip route command
The syntax for ip route command is:
Some important commands in ip route are:
- add: to add a new route
- delete: to delete a route
- change: to change a route
- list: to list the routes
Different examples to use ip route command
1. List current routing table using ip route command
You can use ip route list or ip route show command to list current routes or routing table.
Sample Output:
2. Add a new route using ip route command
The ip route add command is used to add a new route for the specified network range. You will need root privileges to execute the command.
Sample Output:
You can also use ip route only to list the routing table.
3. Add a new default gateway route using ip route command
A default gateway is the IP address of the router that connects your host to remote networks. You can use the following command to add a new default gateway route.
Sample Output:
4. Add a new route to specific device with ip route command
The below command adds a new route specifying the network interface or network device as the gateway.
Sample Output:
5. Delete a route using ip route command
You can use the ip route delete command to delete a route from the routing table.
Sample Output:
6. Modify an existing route using ip route command
You can change a route using the ip route change command.
Sample Output:
For example, to change the default gateway route, you can use the below command.
7. Clear routes with flush using ip route command
The ip route flush command clears a route from the routing table for a particular destination.
Sample Output:
8. Clear all the routes using ip route command
You can also use ip route flush command to remove all the routes from the routing table.
Sample Output:
9. Get a single route to a destination
The below command is used to get a single route to a destination address and prints its contents.
Sample Output:
10. Get a single route from the source
You can run the following command to get a single route from the source address.
Sample Output:
11. List routes with given scope only
You can run the below command to list routes with the given scope only.
Sample Output:
12. List routes for specified device only
The following command lists the routes with the specified device only.
Sample Output:
To view the routes with device name enp0s3, you can use:
Conclusion
In this tutorial, we have learned how we can manage the routing table using the ip route command in the Linux system. You can add, delete, change, and list the routes in the routing table. If you still have any confusion, feel free to ask us in the comment section.
What’s Next
Further Reading
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
How to Add and Delete Static Route in Linux using IP Command
Part of the skill set for any Linux user, and particularly a systems administrator, is the ability to perform some network tweaks on a Linux system. This includes adding and deleting routes to enable the system to communicate with other systems o a local network. In this guide, we explore exactly how you can go about adding and deleting routes on a Linux system.
Viewing the existing routing table
Before we embark on adding or deleting routes, it’s prudent to check the existing default routes on a system. To do so, simply launch your terminal and issue the command:
Similar statistics can be displayed using route command,
Also, you can use the good old netstat command, which is usually used for printing interface statistics as well as the routing table to achieve the same result.
With the default routing statistics in mind, let’s now move a step further and add some routes to our system.
Adding a static route using IP command
Suppose you want to take a backup of a Linux machine and push the backup file to another backup server in the subnet 10.0.2.0/24 . However, for one reason or the other, you cannot reach the backup server via the default gateway. In this case, you will have to create a new route for backup server subnet via another IP, say 192.168.43.223 via the interface enp0s3 .
The command for this will be
- 10.0.2.0 -> is the network you want to connect to
- /24 -> is the subnet mask
- 192.168.43.223 -> is the IP through which we will reach the server
- enp0s3 -> is the network interface
You can confirm whether new static route add been in route table using “ip route show” command.
To add the specific IP of the backup server, say 10.0.2.15 run the command:
Once again, you can check the routing changes to see if the changes exist using the ip route show command:
Permanently adding static route (RHEL, Fedora, CentOS)
The routes we have just added are temporary and will not survive a reboot. To make the routes persistent, you need to manually add them.
In the /etc/sysconfig/network-scripts/ directory, create an interface file route-interface where the interface attribute is your network interface name. In our case, this will be route-enp0s3 .
Next, we will add the routes as shown:
Save the file and exit. Then restart NetworkManager Service
Permanently adding static route (Ubuntu / Debian)
For Debian distributions, edit the file /etc/network/interfaces
Append the following line:
Save and exit the file. Finally, for the changes to come into effect, run below commands
Deleting a static route
To delete a specific route, use the ip route del command. For example, to remove the route address we just added, run the command:
To delete a single IP route in a subnet run the command
To delete default route run:
To add a default route run below ‘ip route add’ command,
$ sudo ip route add default via <ip-address> dev interface
We hope that this tutorial was informative and provided you with insights into how you can go about adding and deleting static route in Linux.
Also Read : 12 ip Command Examples for Linux Users
The Route Add Command in Linux
This tutorial explains the route command and how to use it in Linux to administrate connectivity between different networks.
This document lets you connect networks through routing methods (static, default, and dynamic) and command line techniques (IP and route add).
At Linux Hint, we optimize our content for both new and experienced users by going straight to the point with practical examples for experienced users and by explaining each step thoroughly to new users together with the examples. Our tutorial requires us to start with theoretical content before the practical examples. If you are an experienced user with routing understanding and only need to learn practical instructions, just scroll down to the practical section or press here.
All steps described in this tutorial include screenshots, making it easy for every Linux user to understand how they are applied.
Introduction to Routing Tables
Routing tables are networking instructions where we specify how network devices can access a different network. For example, if we have the network 192.168.0.0 and network 10.0.0.0, we can use routing tables to allow both networks’ connectivity. To achieve connectivity, we specify the path (route) packets that must follow through routing tables. For example, our routing table can determine what routers need to be reached to communicate with different networks.
The command you are looking for, route add, is the command to interact with the routing table, the command to add proper routes to reach the destination or multiple destinations. You can add more than one gateway to access different networks depending on the chosen routing method explained below.
It is also essential to know that those network devices allowing connectivity between two networks is called “gateways”. Gateways must have two network cards, each connected to the networks we want to connect between them.
Static vs. Default vs. Dynamic Routing
There are three different methods to implement network routing: static, default, and dynamic. Each has advantages and disadvantages depending on the network topology and knowledge. They are explained below in this article.
The Static Routing
Static routes are the most specific ones. The static route means both networks must configure their network devices (one by one), instructing the full path (route) each device from each network must follow to reach the other network. It is essential to understand that when using a static route, all devices like computers must be configured manually.
Let’s say you have two different networks, each with its router: the network 192.168.1.x and network 10.0.0.1. The 192.168.1.0 (network A) and 10.0.0.1 (network B) want to connect between them.
Suppose a client from network A wants to connect to network B. In that case, he must specify in the routing table the network destination (B) and all the routers (gateways) it needs to pass through to reach network B. If the network B wants to connect to the network A, each network B client must also be configured reciprocally. There are no automatic inverse connections.
This means if we have a network with a router each and an intermediating third router, we need to configure our client PCs, specifying the network interface or network address and netmask the local router needs to use to communicate with the next router (the intermediating router, the third one). Since the intermediating router is not directly connected to the destination network, the client must also add to the routing table the next router the intermediating one must follow until reaching the destination network. The last router does not need to be configured because it is already directly connected to the destination network.
As said previously, routing devices must have two network cards or interfaces to communicate with both networks.
Let’s take the image below as an example. If a computer from the NETWORK 1 wants to connect to a computer from NETWORK 2 using static routing, the computer from the NETWORK 1 must define in the routing table that both exit interfaces, ROUTER 1 and Intermediating router, need to be used to connect to the next router until reaching the final destination.
When using static routing, the computer must also define the outgoing interface to connect to the intermediating router and the interface the intermediating router needs to use to connect to the router belonging to NETWORK 2. However, the NETWORK 2 router does not need to be specified in the routing table because it is already connected directly to the destination.
If a client from the NETWORK 2 wants to connect to NETWORK 1 (Inverse), it also will be required to add the inverse route or path (including its router but without including the NETWORK 1 router, which is already connected to NETWORK 1).
Static routes are the fastest and safest routing method. It is fast because clients provide routing devices the full path, while routers must learn them by themselves in other methods.
And it is safe because sysadmins hold full knowledge of the network topology, and packets go precisely through the defined route (Path).
The most significant disadvantage of static routing is that each client must be configured manually, which is not practical for big networks.
It is called “static” because each client predefines routes.
Default Routing
While static routes require the client to add the full path to the destination, the default route only requires adding to the routing table the second hop after the local router. The second router, without instructions from the network table, sends the packets to the next hop or router, hoping it will resolve the destination or forward the packet to another router that possibly can determine the goal. This process repeats until the destination is resolved unless some routers cannot route the packet to another device. In such a case, the packet is dropped.
The default route does not necessarily replace static or dynamic routing but remains the last resource in case a destination is not defined through static or dynamic routing. Indeed, the default route is also called “the last resource”. Sometimes, you can have only the default gateway, for example, when we connect to the internet. Then, the connection continues as dynamic.
Dynamic Routing
Dynamic routing is when there are no routing tables, and routers exchange or share all their information with other routers. They learn the network topology by sharing information. As said previously, with static routes, the packet is dropped if some router defined in the path is unavailable. Contrary to static routing, the dynamic one in such cases looks for an alternative since it does not have a predefined route.
Practical Introduction to the Route Command
Before adding or removing routing tables, let’s see how you can print existing routes. You can do it by running the IP route or route commands with superuser permissions, as shown below.
Note: To use the sudo route add command, you must install the net-tools package.
The screenshot above shows that the default gateway is my router with IP address 192.168.0.1, connected through the wlp3s0 device and getting the IP address from DHCP.
The second and third lines are irrelevant. The second is generated in case of an IP assignment problem, and the kernel assigned the third line.
If you have installed the net-tools package on your computer, you can also run the following command to see the existing tables.
The Route Add Command in Linux for Static Routing
Therefore, if my IP address is 192.168.0.103, and I want to connect to the network 192.168.1.0, which is connected through a router (with two interfaces) with the IP address 192.168.3.0, run the command shown in the following figure:
You can do the same using the IP command with the following syntax.
The Route Add Command To Define the Default Gateway in Linux
The syntax is shown below if you want to add a default gateway using the route add command.
If I want to add a default gateway to access the internet and my router has the IP address 192.168.0.1, I would execute the following command:
The same can be done with the IP command shown below:
Making Your Changes Persistent
All changes you make in the routing table will be automatically deleted upon reboot or if the network service restarts.
Run the following command to make routing table changes persistent on Debian or Ubuntu.
Add the following line at the end of the screen shown in the previous screenshot.
In CentOS systems, you need to edit the /etc/sysconfig/network-scripts file and add the following line:
Deleting Route Tables in Linux
If you want to remove the default gateway, you can run the following command (based on previous examples):
Both methods are acceptable.
Conclusion
As you can see, understanding routing tables is easy as long you have basic networking knowledge. From the middle level, there are no pretexts to avoid this subject. This may save you if you try to connect to a network failing to assign you an IP address with DHCP requiring you to fully configure your device with a proper IP address and the correct routing table. It is essential to say the route add command was replaced by the IP route add command. However, most sysadmins still use the first command belonging to the net-tools package (I recommend you to install it), which includes additional features such as the ifconfig command. Many users consider net-tools methods to be easier. Others also prefer it despite the IP command implementing additional features. The important thing is both methods are acceptable and give the same results. You don’t need to learn both of them as long as you know how to read their man pages.
Thank you very much for reading this article explaining routing tables and using the “route add” command. Keep following us for more professional Linux tutorials.
About the author
David Adams
David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.
Как установить / Добавить статические маршруты в Linux? (static routes)
Многие пользователи Linux знакомы с концепцией static routes — маршрута по умолчанию.
Static routes — это маршрут, который ваш компьютер автоматически использует, когда ему нужно направить трафик в определенное место назначения. Но что делать, если вам нужно использовать другой маршрут для определенных доменов? В этой статье мы покажем вам, как создавать собственные маршруты для определенных доменов в Linux.
Некоторые системы предпочитают использовать определенные маршруты для связи между различными частями операционной системы. Например, в системе на основе Unix маршрут по умолчанию может использоваться для отправки трафика, предназначенного для карты сетевого интерфейса (NIC), в соответствующий модуль ядра.
Знание того, какой маршрут используется, может помочь в устранении неполадок.
Как выбрать правильный маршрут для определенного домена в Linux?
При выборе маршрута для определенного домена в Linux важно учитывать шаблоны трафика и требования вашей сети. Существует несколько различных маршрутов, которые можно выбрать в зависимости от потребностей вашей сети. Ниже приведены 2 различных способа, которые можно использовать при маршрутизации трафика в Linux:
Статический маршрут: статический маршрут определяется один раз и никогда не меняется. Это наиболее распространенный тип маршрута, используемый в Linux, поскольку его легко настроить и он не требует настройки маршрутизаторов или брандмауэров.
Динамический маршрут: динамический маршрут создается каждый раз, когда пакет проходит через систему. Этот тип маршрута может быть более сложным в настройке, но он обеспечивает большую гибкость, поскольку может автоматически обновляться в зависимости от изменений в сети.
Чтобы вывести текущую таблицу маршрутизации в Linux выполните команду:
- default via 192.168.1.1 dev enp0s3 – шлюз по умолчанию, в данном примере работающий через интерфейс enp0s3 . Если для target адреса в таблице маршрутизации отсутствует маршрут, то такой пакет отправляется через данный шлюз (маршрут по умолчанию)
- 192.168.1.0/24 dev enp0s3 proto kernel scope link src 192.168.1.201 — статический маршрут для сети 192.168.1.0/24 через адрес 192.168.1.201 , который прописан на интерфейсе
- proto kernel – маршрут создан ядром ( proto static – маршрут добавлен администратором)
- metric – приоритет маршрута (чем меньше значение metric , тем выше приоритет). При наличии двух маршрутов с одинаковой метрикой (не стоит так делать!), ядро начинает выбирать маршруты случайным образом. Чтобы узнать через какой интерфейс (шлюз) должен маршрутизироваться трафик к определенному IP адресу используется команда:
Как найти лучший маршрут DNS для вашего веб-сервера в Linux?
Мы покажем вам, как использовать команду route для поиска наилучшего DNS-маршрута для вашего веб-сервера.
Команда routed — это мощный инструмент, который можно использовать для управления сетевым трафиком в Linux.
С помощью команды route вы можете определить, какие пакеты следует пересылать через ваш сервер, исходя из их адресов назначения. Это может быть полезно, если вам нужно настроить свой сервер определенным образом, например, направить весь трафик для определенного домена через ваш веб-сервер.
Чтобы использовать команду route, вам сначала нужно знать, для какого доменного имени вы хотите направить трафик. Вы можете найти эту информацию, обратившись к своему провайдеру DNS или заглянув в файл /etc/hosts .
В этом видео рассказывается о команде добавления маршрута в Linux. Это базовый дизайн для интернет-протокола. Этот протокол помогает передавать пакеты на нужные машины.
Синтаксис команды route
Какой маршрут Linux подходит для вашего сайта?
Linux предлагает множество способов маршрутизации трафика на определенные сайты. Это может быть полезно, когда вам нужно контролировать, как пользователи получают доступ к определенным частям вашего сайта, или когда вы хотите управлять нагрузкой трафика на определенные разделы вашего сайта.
В Linux есть три основных способа маршрутизации трафика:
- по прямому маршруту,
- непрямым путем,
- и через прокси-сервер.
Прямая маршрутизация — самый простой тип маршрутизации, использующий IP-адрес сайта назначения в качестве исходного адреса для исходящих пакетов.
Этот подход лучше всего подходит для сайтов, которым требуется постоянный уровень безопасности и надежности.
Косвенная маршрутизация предполагает отправку пакетов через один или несколько промежуточных узлов до того, как они достигнут пункта назначения.
Этот подход может повысить производительность, поскольку он уменьшает количество запросов, необходимых для достижения целевого сайта. Однако непрямая маршрутизация также может создавать уязвимости, если промежуточные узлы скомпрометированы.
Как оптимизировать трафик Linux для экономии пропусканой способности?
Linux — мощная операционная система, которую можно использовать для оптимизации трафика в сети. Можно направить трафик для определенных доменов через сервер Linux, чтобы сэкономить пропускную способность. Этот тип оптимизации может быть полезен, если у вас много трафика, поступающего с одного домена, и вы хотите перенаправить его через свой сервер.
Как проверить, работает ли сайт в Linux?
Запуск веб-сайта в Linux может быть отличным вариантом для тех, кто хочет сэкономить на расходах на хостинг или хочет запустить свой сайт, не полагаясь на стороннее доменное имя и имя хоста вашего веб-сайта.
Если вы используете собственное доменное имя, вы можете использовать команду route для доступа к Queervices . Однако, чтобы убедиться, что ваш веб-сайт работает в Linux, важно проверить DNS-сервер на наличие имени хоста вашего сайта.
Если вы используете размещенное доменное имя, вы можете связаться с вашим хостинг-провайдером, чтобы узнать имя хоста вашего сайта. Кроме того, вы можете использовать расширение веб-браузера, например WhoIsHostingThis, чтобы определить имя хоста вашего сайта.
Стриминг Hulu с помощью VPN: сохраняйте конфиденциальность
Если вы хотите получить доступ к Hulu через VPN, сохраните конфиденциальность. Hulu принадлежит Disney, и поэтому на него распространяется ряд ограничений и правил. Они варьируются от требования к зрителям соблюдать законы об авторском праве до блокировки определенных типов рекламы.
Кроме того, известно, что Hulu занимается отслеживанием данных. Используя VPN, вы можете защитить свою конфиденциальность и сохранить приватность своих действий в Интернете.
Заключительные слова
Важно знать, какой маршрут для конкретного домена будет наиболее эффективным для ваших нужд. У вас есть много вариантов, поэтому важно провести исследование, чтобы найти лучший вариант для ваших нужд.