How To Add or Change Default Route or Default Gateway in Ubuntu, Linux?
Systems connected to the network will generally access to the internet. In order to access to the internet they need some network configuration like gateway or default gateway. In this tutorial we will examine how to add or change default gateway in Ubuntu, Debian, CentOS, Fedora, Mint, Kali operating systems.
List Routing Table
Routing table is used to route IP network communication. Hosts generally uses default route to send packages which will redirect them accordingly to transmit destination. We will start by listing current routing table. We will use ip route show command like below.
List Routing Table
Our default gateway line is
- default means this line is default gateway
- via 192.168.122.1 specifies next hop which is default gateway IP address
- dev ens3 is the interface we want use to access default gateway
Remove Existing Default Gateway
Removing default gateway is easy if we list routing table because routing table line is used with del command like below. But keep in mind if you are connecting system remotely from different network which means if you are using default route you connection will be lost.
- ip route del is our key line which deletes specified default gateway
- default via 192.168.122.1 dev ens3 is the same as routing table
Add New Default Gateway
As stated previously default gateway is used to send packages in order to transmit to the destination. We can add new default gateway with the ip route add command like below.
- ip route add will add provided default gateway
- default means target network is all which is default
- via 192.168.1.1 is our default gateway network address
- dev ens3 is network interface for default gateway
Check
List routing table again and ping some of remote networks will give the status of default gateway
How To Add or Change Default Route or Default Gateway in Ubuntu, Linux? Infografic
How can I change the default gateway?
Currently I’m running a FreeBSD 9.1 and the default gateway is already configured in the rc.conf .
But now I want to change the default gateway without rebooting the system, is this possible?
7 Answers 7
Where 1.2.3.4 is the new gateway. You can even concatenate them onto the same line with a ;
Edit: This is FreeBSD, not Linux. The command is different. Please do not edit this Answer if you haven’t read the Question carefully enough to determine the operating system being used.
You can add a new default route and remove the old one using either the ip or route command. The commands below will replace the gateway with 192.0.2.1. Both command pairs do the same thing. FreeBSD and other OSs should have one or both programs, possibly with slightly different formats. (FreeBSD has the route command and excludes the gw keyword used in other implementations.) The commands man ip and/or man route should provide you with documentation on your specific implementation.
There are multiple implementations of these commands, so the above may not match your implementation. Your implementation should have a man page with examples for common use cases such as adding and removing default gateways. Try man route and man ip to see how your implementation works.
Change 192.0.2.1 to your desired default gateway. The default gateway needs to be on one of networks you have a direct connection to. You can change your IP address in a similar manner. ip is a newer tool which will do most everything you need to do to view and manage IP addresses and routing on IPv4 and IPv6 networks. ifconfig is an an older tool for configuring IP addresses on an IPv4 network.
To make the change permanent, update your network configuration files in /etc . The file(s) vary depending on the distribution you are using.
At least one of these commands should be available on any Unix derived O/S. Different versions may work slightly differently. Check the man page for details on your O/S.
Linux setup default gateway with route command
[donotprint]Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | Yes |
Requirements | None |
Time | 5m |
[/donotprint]The route command manipulates the kernel’s IP routing tables. Its primary use is to set up static routes to specific hosts or networks via an interface after it has been configured with the ifconfig program. When the add or del options are used, route modifies the routing tables. Without these options, route displays the current contents of the routing tables.
Display default route
Following three-command display the current routing table:
# route
Output:
OR
$ /sbin/route
Output:
You can use -n option, to display numerical addresses instead of trying to determine symbolic host names (via dns or /etc/hosts file). This is useful if you are trying to determine why the route to your nameserver has vanished.
$ /sbin/route -n Output:
Please note that a destination entry 0.0.0.0 (or default) is the default gateway. In above example 191.255.255.1 is a default gateway.
Add / setup a new route
The syntax is as follows:
- IP-ADDRESS: Specify router IP address
- INTERFACE-NAME: Specify interface name such as eth0
For example if your router IP address is 192.168.1.254 type the following command as the root user:
# route add default gw 192.168.1.254 eth0
OR use hostname such as dsl-router:
# route add default gw dsl-router eth0
Or use the ip command (newer syntax) to route all traffic via 192.168.1.254 gateway connected via eth0 network interface:
# ip route add 192.168.1.0/24 dev eth0
OR
# ip route add 192.168.1.0/24 via 192.168.1.254
Setting route using GUI tools/command under Linux
If you find above command hard to use, consider using GUI tools. If your are using Red Hat/CentOS/Fedora core Linux type following command: # redhat-config-network OR If you are using other Linux distribution use command: # network-admin
How to set the Default gateway
I’m trying to configure the network interface on embedded linux using ifconfig:
but I don’t know how to add the default gateway as an ifconfig parameter,
4 Answers 4
ifconfig is not the correct command to do that.
You can use route like in route add default gw 192.168.0.254 for example.
And if route is not present, but ip is, you can use it like this: ip route add default via 192.168.0.254 dev eth0 , assuming that 192.168.0.254 is the ip of your gateway
ifconfig is deprecated on Linux and furthermore, it’s the wrong tool for the job. To set the default gateway on Linux use the ip command as follows:
example: route add default gw 192.168.1.2 eth0
OR use hostname such as dsl-router:
Or use the ip command (newer syntax) to route all traffic via 192.168.1.254 gateway connected via eth0 network interface for example:
ИТ База знаний
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Популярное и похожее
15 примеров команды PING для диагностики сети
15 примеров CURL в Linux
Руководство по команде grep в Linux
Установка и настройка ClamAV Linux
11 утилит сканирования Linux серверов на уязвимости и вредоносы
Использование опций команды apt-get для очистки системы
Как настроить редирект с HTTP на HTTPS в Nginx
Openvox DGW-1001
Еженедельный дайджест
Настройка маршрута по умолчанию в Linux
В любой непонятной ситуации
В статье мы покажем, как использовать команды маршрутизации в Linux (в UNIX подобных системах) чтобы отображать или конфигурить информацию о дефолтных маршрутах. Погнали разбираться!
Показать маршруты по умолчанию
Ловите 2 команды, которые помогут отобразить текущую таблицу маршрутизации в Linux:
Вывод такой команды будет примерно следующим:
Или можно использовать второй вариант:
”Выхлоп” такой команды в той же самой таблице маршрутизации:
Настройка дефолтного маршрута
Синтаксис настройки категорически прост. Смотрите:
- IP-АДРЕС — IP — адрес шлюза;
- ИНТЕРФЕЙС — имя интерфейса, за которым сидит указанный выше шлюз;
Например, если IP — адрес вашего роутера 192.168.1.254 и он сидит на интерфейсом eth0, то из под root выполните команду:
Или можно использовать хостнейм (только проверьте, чтобы он резолвился на уровне DNS):
Или можно использовать команду ip , чтобы маршрутизировать весь трафик через шлюз 192.168.1.254, который подключен к интерфейсу eth0:
Либо вместо eth0 интерфейса можно прописать в явном виде адрес шлюза. Тут ап ту ю, как говорится 🙂
Было полезно?
Почему?
😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.
😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.