Загрузить PDF
Загрузить PDF
Основной шлюз (шлюз по умолчанию) — это IP-адрес вашего маршрутизатора. Обычно он автоматически определяется операционной системой во время установки, но, возможно, вам нужно изменить его. Это особенно актуально, если в сети есть несколько сетевых адаптеров или маршрутизаторов.
-
1
Запустите терминал. Щелкните по нему на боковой панели или нажмите Ctrl+Alt+T.
-
2
Найдите адрес активного основного шлюза. Для этого введите route и нажмите ↵ Enter. В строке «default» (по умолчанию) отобразится адрес основного шлюза, а назначенный ему интерфейс можно найти в правой части таблицы.
-
3
Удалите активный основной шлюз. Если установлено несколько основных шлюзов, они могут конфликтовать. Удалите активные основной шлюз, если собираетесь менять его.
- Введите sudo route delete default gw IP-адрес Адаптер. Например, чтобы удалить основной шлюз 10.0.2.2 адаптера eth0, введите sudo route delete default gw 10.0.2.2 eth0.
-
4
Введите sudo route add default gw IP-адрес Адаптер. Например, чтобы изменить основной шлюз адаптера eth0 на 192.168.1.254, введите sudo route add default gw 192.168.1.254 eth0. Вам будет предложено ввести пароль пользователя, чтобы выполнить команду.
Реклама
-
1
Откройте файл конфигурации в редакторе. Введите sudo nano /etc/network/interfaces, чтобы открыть файл в редакторе nano. Внесенные изменения будут храниться до следующей перезагрузки системы.
-
2
Перейдите в нужный раздел. Найдите раздел адаптера, основной шлюз которого вы хотите изменить. Адаптер проводного подключения называется eth0.
-
3
В раздел добавьте строку gateway IP-адрес. Например, введите gateway 192.168.1.254, чтобы присвоить основному шлюзу адрес 192.168.1.254.
-
4
Сохраните внесенные изменения. Нажмите Ctrl+X, а затем нажмите Y, чтобы сохранить изменения и выйти из текстового редактора.
-
5
Перезагрузите сеть. Для этого введите sudo /tc/init.d/networking restart.[1]
Реклама
Об этой статье
Эту страницу просматривали 60 819 раз.
Была ли эта статья полезной?
Download Article
Download Article
If you need to find or change the IP address of your default gateway or router on Linux, you’re in luck—it’s super easy to do. This wikiHow article will show you how to use the route command to find the default gateway IP address on Linux, and how to set a new default gateway in your /etc/network/interfaces configuration file.
-
1
Open the Terminal. You can open the Terminal from the side bar, or by pressing Ctrl+Alt+T.[1]
-
2
View your current default gateway. You can check what your default gateway is set to by typing route and pressing ↵ Enter. The address next to «default» shows your default gateway, and the interface it is assigned to is displayed on the right side of the table.
Advertisement
-
3
Delete your current default gateway. If you have more than one default gateway set, you’ll run into connection conflicts. Delete your existing default gateway if you intend to change it.[2]
- Type sudo route delete default gw IP Address Adapter. For example, to delete the default gateway 10.0.2.2 on the eth0 adapter, type sudo route delete default gw 10.0.2.2 eth0.
-
4
Type .sudo route add default gw IP Address Adapter. For example, to change the default gateway of the eth0 adapter to 192.168.1.254, you would type sudo route add default gw 192.168.1.254 eth0.[3]
You’ll be prompted for your user password in order to complete the command.
Advertisement
-
1
Open the configuration file in an editor. Type sudo nano /etc/network/interfaces to open the file in the nano editor. Editing your configuration file will keep your changes every time the system restarts.[4]
-
2
Navigate to the correct section. Find the section for the adapter you want to change the default gateway for. For a wired connection, this is usually eth0.
-
3
Add .gateway IP Address to the section. For example, type gateway 192.168.1.254 to make the default gateway 192.168.1.254.[5]
-
4
Save your changes and exit. Press Ctrl+X and then Y to save your changes and exit.
-
5
Restart your network. Restart your network by typing sudo /etc/init.d/networking restart.[6]
Advertisement
Add New Question
-
Question
Will the admins know if I change my IP?
Yes, if they chose to check.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
Thanks for submitting a tip for review!
About This Article
Article SummaryX
1. Open a terminal window.
2. Type «sudo route delete default gw (IP) (Adapter)» and press Enter.
3. Type «sudo route add default gw (IP) (Adapter)» and press Enter.
4. Open /etc/network/interfaces in a text editor.
5. Update the gateway IP address for the adapter.
6. Save your changes and exit the editor.
7. Type «sudo /etc/init.d/networking restart» and press Enter.
Did this summary help you?
Thanks to all authors for creating a page that has been read 951,719 times.
Is this article up to date?
Download Article
Download Article
If you need to find or change the IP address of your default gateway or router on Linux, you’re in luck—it’s super easy to do. This wikiHow article will show you how to use the route command to find the default gateway IP address on Linux, and how to set a new default gateway in your /etc/network/interfaces configuration file.
-
1
Open the Terminal. You can open the Terminal from the side bar, or by pressing Ctrl+Alt+T.[1]
-
2
View your current default gateway. You can check what your default gateway is set to by typing route and pressing ↵ Enter. The address next to «default» shows your default gateway, and the interface it is assigned to is displayed on the right side of the table.
Advertisement
-
3
Delete your current default gateway. If you have more than one default gateway set, you’ll run into connection conflicts. Delete your existing default gateway if you intend to change it.[2]
- Type sudo route delete default gw IP Address Adapter. For example, to delete the default gateway 10.0.2.2 on the eth0 adapter, type sudo route delete default gw 10.0.2.2 eth0.
-
4
Type .sudo route add default gw IP Address Adapter. For example, to change the default gateway of the eth0 adapter to 192.168.1.254, you would type sudo route add default gw 192.168.1.254 eth0.[3]
You’ll be prompted for your user password in order to complete the command.
Advertisement
-
1
Open the configuration file in an editor. Type sudo nano /etc/network/interfaces to open the file in the nano editor. Editing your configuration file will keep your changes every time the system restarts.[4]
-
2
Navigate to the correct section. Find the section for the adapter you want to change the default gateway for. For a wired connection, this is usually eth0.
-
3
Add .gateway IP Address to the section. For example, type gateway 192.168.1.254 to make the default gateway 192.168.1.254.[5]
-
4
Save your changes and exit. Press Ctrl+X and then Y to save your changes and exit.
-
5
Restart your network. Restart your network by typing sudo /etc/init.d/networking restart.[6]
Advertisement
Add New Question
-
Question
Will the admins know if I change my IP?
Yes, if they chose to check.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
Thanks for submitting a tip for review!
About This Article
Article SummaryX
1. Open a terminal window.
2. Type «sudo route delete default gw (IP) (Adapter)» and press Enter.
3. Type «sudo route add default gw (IP) (Adapter)» and press Enter.
4. Open /etc/network/interfaces in a text editor.
5. Update the gateway IP address for the adapter.
6. Save your changes and exit the editor.
7. Type «sudo /etc/init.d/networking restart» and press Enter.
Did this summary help you?
Thanks to all authors for creating a page that has been read 951,719 times.
Is this article up to date?
I’m trying to configure the network interface on embedded linux using ifconfig:
ifconfig eth0 192.168.0.101 netmask 255.255.255.0
but I don’t know how to add the default gateway as an ifconfig parameter,
Any Ideas?
Rui F Ribeiro
54.8k26 gold badges144 silver badges221 bronze badges
asked Feb 1, 2016 at 11:01
1
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
evandrix
1572 silver badges5 bronze badges
answered Feb 1, 2016 at 11:07
1
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:
ip route add default via <host> dev <dev>
# e.g.
ip route add default via 192.168.0.101 dev eth0
answered Feb 1, 2016 at 11:12
MarcoMarco
32.6k10 gold badges111 silver badges144 bronze badges
For remove gateway in Linux Command : route delete default gw 192.168.1.1 eth1
For add gateway in Linux Command : route add default gw 192.168.1.250 eth1
mrc02_kr
1,90315 silver badges31 bronze badges
answered Sep 5, 2017 at 6:51
Using route
route add default gw {IP-ADDRESS} {INTERFACE-NAME}
example: route add default gw 192.168.1.2 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 for example:
ip route add 192.168.1.0/24 dev eth0
or
ip route add 192.168.1.0/24 via 192.168.1.254
answered Feb 1, 2016 at 11:22
GAD3RGAD3R
61k30 gold badges126 silver badges189 bronze badges
Ubuntu ships with a number of graphical utilities to configure your network devices. This document is geared toward server administrators and will focus on managing your network on the command line.
Ethernet interfaces
Ethernet interfaces are identified by the system using predictable network interface names. These names can appear as eno1 or enp0s25. However, in some cases an interface may still use the kernel eth# style of naming.
Identify Ethernet interfaces
To quickly identify all available Ethernet interfaces, you can use the ip command as shown below.
ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: enp0s25: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 00:16:3e:e2:52:42 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 10.102.66.200/24 brd 10.102.66.255 scope global dynamic eth0
valid_lft 3257sec preferred_lft 3257sec
inet6 fe80::216:3eff:fee2:5242/64 scope link
valid_lft forever preferred_lft forever
Another application that can help identify all network interfaces available to your system is the lshw
command. This command provides greater details around the hardware capabilities of specific adapters. In the example below, lshw
shows a single Ethernet interface with the logical name of eth4 along with bus information, driver details and all supported capabilities.
sudo lshw -class network
*-network
description: Ethernet interface
product: MT26448 [ConnectX EN 10GigE, PCIe 2.0 5GT/s]
vendor: Mellanox Technologies
physical id: 0
bus info: pci@0004:01:00.0
logical name: eth4
version: b0
serial: e4:1d:2d:67:83:56
slot: U78CB.001.WZS09KB-P1-C6-T1
size: 10Gbit/s
capacity: 10Gbit/s
width: 64 bits
clock: 33MHz
capabilities: pm vpd msix pciexpress bus_master cap_list ethernet physical fibre 10000bt-fd
configuration: autonegotiation=off broadcast=yes driver=mlx4_en driverversion=4.0-0 duplex=full firmware=2.9.1326 ip=192.168.1.1 latency=0 link=yes multicast=yes port=fibre speed=10Gbit/s
resources: iomemory:24000-23fff irq:481 memory:3fe200000000-3fe2000fffff memory:240000000000-240007ffffff
Ethernet Interface logical names
Interface logical names can also be configured via a Netplan configuration. If you would like control which interface receives a particular logical name use the match
and set-name
keys. The match
key is used to find an adapter based on some criteria like MAC address, driver, etc. The set-name
key can be used to change the device to the desired logical name.
network:
version: 2
renderer: networkd
ethernets:
eth_lan0:
dhcp4: true
match:
macaddress: 00:11:22:33:44:55
set-name: eth_lan0
Ethernet Interface settings
ethtool
is a program that displays and changes Ethernet card settings such as auto-negotiation, port speed, duplex mode, and Wake-on-LAN. The following is an example of how to view the supported features and configured settings of an Ethernet interface.
sudo ethtool eth4
Settings for eth4:
Supported ports: [ FIBRE ]
Supported link modes: 10000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: No
Supported FEC modes: Not reported
Advertised link modes: 10000baseT/Full
Advertised pause frame use: No
Advertised auto-negotiation: No
Advertised FEC modes: Not reported
Speed: 10000Mb/s
Duplex: Full
Port: FIBRE
PHYAD: 0
Transceiver: internal
Auto-negotiation: off
Supports Wake-on: d
Wake-on: d
Current message level: 0x00000014 (20)
link ifdown
Link detected: yes
IP addressing
The following section describes the process of configuring your system’s IP address and default gateway needed for communicating on a local area network and the Internet.
Temporary IP address assignment
For temporary network configurations, you can use the ip
command which is also found on most other GNU/Linux operating systems. The ip
command allows you to configure settings which take effect immediately – however they are not persistent and will be lost after a reboot.
To temporarily configure an IP address, you can use the ip
command in the following manner. Modify the IP address and subnet mask to match your network requirements.
sudo ip addr add 10.102.66.200/24 dev enp0s25
The ip
can then be used to set the link up or down.
ip link set dev enp0s25 up
ip link set dev enp0s25 down
To verify the IP address configuration of enp0s25
, you can use the ip
command in the following manner:
ip address show dev enp0s25
10: enp0s25: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 00:16:3e:e2:52:42 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 10.102.66.200/24 brd 10.102.66.255 scope global dynamic eth0
valid_lft 2857sec preferred_lft 2857sec
inet6 fe80::216:3eff:fee2:5242/64 scope link
valid_lft forever preferred_lft forever6
To configure a default gateway, you can use the ip
command in the following manner. Modify the default gateway address to match your network requirements.
sudo ip route add default via 10.102.66.1
You can also use the ip
command to verify your default gateway configuration, as follows:
ip route show
default via 10.102.66.1 dev eth0 proto dhcp src 10.102.66.200 metric 100
10.102.66.0/24 dev eth0 proto kernel scope link src 10.102.66.200
10.102.66.1 dev eth0 proto dhcp scope link src 10.102.66.200 metric 100
If you require DNS for your temporary network configuration, you can add DNS server IP addresses in the file /etc/resolv.conf
. In general, editing /etc/resolv.conf
directly is not recommended, but this is a temporary and non-persistent configuration. The example below shows how to enter two DNS servers to /etc/resolv.conf
, which should be changed to servers appropriate for your network. A more lengthy description of the proper (persistent) way to do DNS client configuration is in a following section.
nameserver 8.8.8.8
nameserver 8.8.4.4
If you no longer need this configuration and wish to purge all IP configuration from an interface, you can use the ip
command with the flush option:
ip addr flush eth0
Note
Flushing the IP configuration using theip
command does not clear the contents of/etc/resolv.conf
. You must remove or modify those entries manually (or re-boot), which should also cause/etc/resolv.conf
, which is a symlink to/run/systemd/resolve/stub-resolv.conf
, to be re-written.
Dynamic IP address assignment (DHCP client)
To configure your server to use DHCP for dynamic address assignment, create a Netplan configuration in the file /etc/netplan/99_config.yaml
. The following example assumes you are configuring your first Ethernet interface identified as enp3s0
.
network:
version: 2
renderer: networkd
ethernets:
enp3s0:
dhcp4: true
The configuration can then be applied using the netplan
command:
sudo netplan apply
Static IP address assignment
To configure your system to use static address assignment, create a netplan
configuration in the file /etc/netplan/99_config.yaml
. The example below assumes you are configuring your first Ethernet interface identified as eth0
. Change the addresses
, routes
, and nameservers
values to meet the requirements of your network.
network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses:
- 10.10.10.2/24
routes:
- to: default
via: 10.10.10.1
nameservers:
search: [mydomain, otherdomain]
addresses: [10.10.10.1, 1.1.1.1]
The configuration can then be applied using the netplan
command.
sudo netplan apply
NOTE
netplan
in Ubuntu Bionic 18.04 LTS doesn’t understand the “to: default
” syntax to specify a default route, and should use the oldergateway4: 10.10.10.1
key instead of the wholeroutes:
block.
The loopback interface is identified by the system as lo
and has a default IP address of 127.0.0.1. It can be viewed using the ip
command.
ip address show lo
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
Name resolution
Name resolution (as it relates to IP networking) is the process of mapping hostnames to IP addresses, and vice-versa, making it easier to identify resources on a network. The following section will explain how to properly configure your system for name resolution using DNS and static hostname records.
DNS client configuration
Traditionally, the file /etc/resolv.conf
was a static configuration file that rarely needed to be changed, or it automatically changed via DCHP client hooks. systemd-resolved
handles nameserver configuration, and it should be interacted with through the systemd-resolve
command. Netplan configures systemd-resolved
to generate a list of nameservers and domains to put in /etc/resolv.conf
, which is a symlink:
/etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf
To configure the resolver, add the IP addresses of the appropriate nameservers for your network to the netplan
configuration file. You can also add optional DNS suffix search-lists to match your network domain names. The resulting file might look like the following:
network:
version: 2
renderer: networkd
ethernets:
enp0s25:
addresses:
- 192.168.0.100/24
routes:
- to: default
via: 192.168.0.1
nameservers:
search: [mydomain, otherdomain]
addresses: [1.1.1.1, 8.8.8.8, 4.4.4.4]
The search option can also be used with multiple domain names so that DNS queries will be appended in the order in which they are entered. For example, your network may have multiple sub-domains to search; a parent domain of example.com
, and two sub-domains, sales.example.com
and dev.example.com
.
If you have multiple domains you wish to search, your configuration might look like the following:
network:
version: 2
renderer: networkd
ethernets:
enp0s25:
addresses:
- 192.168.0.100/24
routes:
- to: default
via: 192.168.0.1
nameservers:
search: [example.com, sales.example.com, dev.example.com]
addresses: [1.1.1.1, 8.8.8.8, 4.4.4.4]
If you try to ping a host with the name server1
, your system will automatically query DNS for its Fully Qualified Domain Name (FQDN) in the following order:
-
server1.example.com
-
server1.sales.example.com
-
server1.dev.example.com
If no matches are found, the DNS server will provide a result of notfound and the DNS query will fail.
Static hostnames
Static hostnames are locally defined hostname-to-IP mappings located in the file /etc/hosts
. Entries in the hosts
file will have precedence over DNS by default. This means that if your system tries to resolve a hostname and it matches an entry in /etc/hosts
, it will not attempt to look up the record in DNS. In some configurations, especially when Internet access is not required, servers that communicate with a limited number of resources can be conveniently set to use static hostnames instead of DNS.
The following is an example of a hosts
file where a number of local servers have been identified by simple hostnames, aliases and their equivalent Fully Qualified Domain Names (FQDN’s):
127.0.0.1 localhost
127.0.1.1 ubuntu-server
10.0.0.11 server1 server1.example.com vpn
10.0.0.12 server2 server2.example.com mail
10.0.0.13 server3 server3.example.com www
10.0.0.14 server4 server4.example.com file
Note
In this example, notice that each of the servers were given aliases in addition to their proper names and FQDN’s. Server1 has been mapped to the name vpn, server2 is referred to as mail, server3 as www, and server4 as file.
Name Service Switch (NSS) configuration
The order in which your system selects a method of resolving hostnames to IP addresses is controlled by the Name Service Switch (NSS) configuration file /etc/nsswitch.conf
. As mentioned in the previous section, typically static hostnames defined in the systems /etc/hosts
file have precedence over names resolved from DNS. The following is an example of the line responsible for this order of hostname lookups in the file /etc/nsswitch.conf
.
hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4
-
files
first tries to resolve static hostnames located in/etc/hosts
. -
mdns4_minimal
attempts to resolve the name using Multicast DNS. -
[NOTFOUND=return]
means that any response ofnotfound
by the precedingmdns4_minimal
process should be treated as authoritative and that the system should not try to continue hunting for an answer. -
dns
represents a legacy unicast DNS query. -
mdns4 represents a multicast DNS query.
To modify the order of these name resolution methods, you can simply change the hosts:
string to the value of your choosing. For example, if you prefer to use legacy unicast DNS versus multicast DNS, you can change the string in /etc/nsswitch.conf
as shown below:
hosts: files dns [NOTFOUND=return] mdns4_minimal mdns4
Bridging multiple interfaces
Bridging is a more advanced configuration, but is very useful in multiple scenarios. One scenario is setting up a bridge with multiple network interfaces, then using a firewall to filter traffic between two network segments. Another scenario is using bridge on a system with one interface to allow virtual machines direct access to the outside network. The following example covers the latter scenario:
Configure the bridge by editing your netplan
configuration found in /etc/netplan/
, entering the appropriate values for your physical interface and network:
network:
version: 2
renderer: networkd
ethernets:
enp3s0:
dhcp4: no
bridges:
br0:
dhcp4: yes
interfaces:
- enp3s0
Now apply the configuration to enable the bridge:
sudo netplan apply
The new bridge interface should now be up and running. The brctl
provides useful information about the state of the bridge, controls which interfaces are part of the bridge, etc. See man brctl
for more information.
networkd-dispatcher for hook scripts
Users of the former ifupdown
may be familiar with using hook scripts (e.g., pre-up, post-up) in their interfaces file. Netplan configuration does not currently support hook scripts in its configuration definition.
Instead, to achieve this functionality with the networkd
renderer, users can use networkd-dispatcher. The package provides both users and packages with hook points when specific network states are reached, to aid in reacting to network state.
Note:
If you are on Desktop (not Ubuntu Server) the network is driven by Network Manager — in that case you need NM Dispatcher scripts instead.
The Netplan FAQ has a great table that compares event timings between ifupdown
/systemd-networkd
/network-manager
.
It is important to be aware that these hooks run asynchronously; i.e. they will not block transition into another state.
The Netplan FAQ also has an example on converting an old ifupdown
hook to networkd-dispatcher
.
Resources
-
The Ubuntu Wiki Network page has links to articles covering more advanced network configuration.
-
The Netplan website has additional examples and documentation.
-
The Netplan man page has more information on Netplan.
-
The systemd-resolved man page has more information on systemd-resolved service.
-
For more information on bridging see the netplan.io examples page
🖧 Команда IP route: создание статических маршрутов или изменение шлюза по умолчанию на Linux
На чтение 3 мин Опубликовано 22.04.2020
Команда IP route является расширением команды IP, которую мы уже кратко обсуждали команды IP в нашем предыдущем уроке.
Команда IP route используется для добавления, удаления или изменения таблицы маршрутизации системы Linux.
Содержание
- Команда Ip route на Linux
- 2- Как создать новый роутинг, т.е. создать новый статический маршрут.
- 3- Удалить маршрут
- 4- Удалить существующий шлюз по умолчанию
- 5- Как добавить новый шлюз по умолчанию
- 6- Как отклонить сетевые пакеты для конкретного хоста или сети
Команда Ip route на Linux
Чтобы проверить текущую таблицу маршрутизации системы, мы можем использовать следующие команды:
# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 10.10.1.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3
или
# route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 10.10.1.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3 0.0.0.0 10.10.1.10 0.0.0.0 UG 0 0 0 enp0s3
Мы также можем использовать следующую команду для проверки маршрутов:
# ip route show
Назначенный системный IP для системы – 10.10.1.100, и мы можем видеть, что пункт назначения находится в этом диапазоне только в первом выводе команды.
Вторая команда также показывает шлюз для диапазона IP, то есть 10.10.1.10.
Файлы маршрутизации находятся в папке «/etc/sysconfig/network-scripts/»:
# cat /etc/sysconfig/network-scripts/route-enp0s3 10.10.1.0/24 via 10.10.1.10 dev enp0s3
2- Как создать новый роутинг, т.е. создать новый статический маршрут.
# ip route add 10.10.3.0/24 dev en0sp3
И мы хотим, чтобы эта сеть направлялась от определенного шлюза:
# ip route add 10.10.3.0/24 via 10.10.1.10 dev en0sp3
3- Удалить маршрут
Чтобы удалить роут:
# ip route delete 10.10.3.0//24 dev en0sp3
4- Удалить существующий шлюз по умолчанию
Чтобы удалить существующий шлюз по умолчанию системы:
# ip route delete default
То же самое можно сделать с помощью команды:
# route delete default
5- Как добавить новый шлюз по умолчанию
Чтобы настроить новый шлюз по умолчанию, нам нужно использовать следующую команду:
# route add default gw 10.10.1.20
или мы также можем использовать следующую команду:
# ip route add default via 10.10.1.20
6- Как отклонить сетевые пакеты для конкретного хоста или сети
Мы также можем использовать команду IP route для запрета сетевого трафика на конкретном хосте или даже для диапазона сети.
Чтобы отклонить сетевые пакеты для одного хоста:
# route add -host 10.10.2.20 reject
Чтобы отклонить сетевые пакеты для всей сети, мы можем использовать следующую команду:
# route add -net 10.10.2.0 netmask 255.0.0.0 reject
Мы обсудили только некоторые важные примеры использования для управления маршрутами в нашей системе.
Пожалуйста, не стесняйтесь присылать любые вопросы, используя поле для комментариев ниже.
Пожалуйста, не спамьте и никого не оскорбляйте.
Это поле для комментариев, а не спамбокс.
Рекламные ссылки не индексируются!
A default gateway is what linux will use to interact with other computers connected on the network. This is typically the router and will send all packets to that IP address. The actions below all use the route command, to find out more possiblities view the route man page.
View the Current Routing Table
To view the current routing table on a linux server you can do the following:
route -n Which will return the following output:
# route -n 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
You can see that the default route is the first line sending all packets to the 192.168.1.1 Gateway.
Remove A Default Gateway
To remove a default route you will need to use the following command, substituting 192.168.1.1 with the IP address of the default route you previously saw
# route del default gw 192.168.1.1
Once you have removed it confirm by doing another route -n
# route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
Add A Default Gateway
To add a new default route you will need to use the following:
route add default gw 192.168.1.1
Once you have added the new route you will see it appear in the routing table:
# route -n 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
Permanently Configure The Default Gateway
To make the new default gateway persist through a reboot, you will need to edit the network interface file:
nano /etc/sysconfig/network-scripts/ifcfg-eth0
Substitute the name of the file with the interface you are setting the route for.
Update or append the following line the file switching out 192.168.1.1 with the IP address of the default router:
GATEWAY=192.168.1.1
Once you have saved the file, you can restart networking to ensure it is working properly
/etc/init.d/networking restart
Jul 5, 2017
3.3 4 votes
Article Rating
To access the internet, a gateway plays a vital role. For accessing other devices on a network or devices like computers, they need to be configured either automatically or manually by a network or system administrator. Communication between different devices is necessary to route data packets when they travel across a network. A system’s routing table decides which network interface should send these packets to remote systems or devices. Network devices are used for this purpose, although routing can be performed by any device configured as a router.
A default gateway is used for traffic not destined for the local network and for which no particular route is preferred inside the routing table. Similarly, traffic of static routes must not or need not pass via a default gateway. Traditionally, a default gateway serves as the dedicated network router.
What will we cover?
This guide will learn how to set up a default gateway on Ubuntu 20.04 (Focal Fossa) OS using the ‘ip route’ and ‘route’ command. Let us get started with this HowTo.
What are the Prerequisites?
Before you start with this tutorial, look at the following requirements:
- Ubuntu 20.04 installed on your system with internet connectivity.
- Root user account or user account with ‘sudo’ privileges.
- Basic knowledge of computer networks and Ubuntu administration.
Precaution: Please note that this is a very advanced technical guide. Only attempt to follow this guide if you know what you are doing. If you are a novice and end up messing with network configuration, you may lose your connection to the internet.
Experimental Setup
For this guide, we will use IP 192.168.56.4 (enp0s8) as the default gateway address, the IP address of one of the interfaces on our Ubuntu machine (VM1). The other interface has a different IP address which is 192.168.57.5 (enp0s3). Now comes the VM2, which has only one interface with IP address 192.168.56.101 (enp0s3). It is clear that VM2 enp0s3 cannot access VM1 enp0s3 as both are on different network addresses.
Our task is to make both VMs communicate on interfaces with different network addresses. We will set the IP of VM1(192.168.56.4) as a gateway for another machine (VM2), and we will then check by pinging VM1 from VM2 to see if it can reach it the gateway.
VM1 | 192.168.56.4 (enp0s8) | 192.168.56.101 (enp0s3) |
VM2 | — | 192.168.57.5 (enp0s3) |
Finding the Default Gateway IP
Let us first check the default gateway that is already set on our machine, for this run the command:
This will display the default gateway on the terminal.
Alternatively, we can use the ‘route’ command for the same purpose:
If you get an error like ‘Command ‘route’ not found’, then you can install the ‘route’ command with:
sudo apt install net-tools
Check the UG flag to look for the Gateway. Routing table flags and their meanings are given below:
U : UP— indicates that the route is up and valid
H : Host— target is to a host
G : Gateway—means that the route is to a gateway
R : Reject— It is set by ARP when an entry is expired
D : Dynamic— Route added by a routing redirect
M : Modified— Route modified by a routing redirect
The output of the above two commands is almost identical. Another way is to use the ‘netstat -rn’ command to check the gateway IP.
Setting Default Gateway Using the ‘ip’ Command
First, we will use the ‘ip’ command to set the default gateway on VM2. For this, follow the steps mentioned below:
Step 1. Open a terminal (Ctrl+Alt+F2) and run the command:
sudo ip route add default via 192.168.56.4
Step 2. Now ping the VM1 from VM2 to check if our gateway is accessible:
To delete the above default route, use the command below:
sudo ip route del default via 192.168.56.4
To confirm the above changes, use the “route -n” command.
Setting Default Gateway Using the ‘route’ Command
Now we will use the ‘route’ command to set the default gateway on VM2. For this, follow the steps mentioned below:
Step 1. Open a terminal (Ctrl+Alt+F2) and run the command:
sudo route add default gw 192.168.56.4
Step 2. Now ping the VM1 from VM2 to check if our gateway is accessible:
To delete the above default route, use the command below:
sudo route del default gw 192.168.56.4
To confirm the above changes, use the “route -n” command.
Conclusion
In this guide, we have learned about setting the default gateway on Ubuntu 20.04. Try to make different scenarios of devices and connect them using a common gateway.