Прописать default gateway linux

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

Источник

Debian / Ubuntu Linux Setting a Default Gateway

Q. How do I setup a default gateway on Debian or Ubuntu Linux? My router IP is 192.168.1.254 and I’d like to setup this as a default gateway for Debian Linux.

A. You can use command line tool such as
a] ip command – show / manipulate routing, devices, policy routing and tunnels

b] route command – show / manipulate the IP routing table

c] Save routing information to a configuration file so that after reboot you get same default gateway.

ip command to set a default router to 192.168.1.254

Login as the root and type:
# ip route add default via 192.168.1.254
OR
$ sudo ip route add default via 192.168.1.254

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard
Читайте также:  Windows server 2012 r2 не работает планировщик задач

Join Patreon

route command to set a default router to 192.168.1.254

Login as the root and type:
# route add default gw 192.168.1.254
OR
$ sudo route add default gw 192.168.1.254

Save routing information to a configuration file /etc/network/interfaces

Open /etc/network/interfaces file
# vi /etc/network/interfaces
OR
$ sudo vi /etc/network/interfaces
Find eth0 or desired network interface and add following option
gateway 192.168.1.254
Save and close the file. Restart networking:
# /etc/init.d/networking restart
OR
$ sudo /etc/init.d/networking restart

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

I also want to set my defualt DNS server and proxy settings, just like in windows. How do I do that ??

In Ubuntu, you can either add the ‘nameserver’ lines in /etc/resolv.conf like “shutty” shows, or use the recommended method in Ubuntu Precise (12.04 LTS) by adding “dns-nameservers ” and “dns-search ” in /etc/network/interfaces, like so:

# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.3.1
netmask 255.255.255.0
# dns-* options are implemented by the resolvconf package, if installed

dns-nameservers 8.8.8.8
dns-search lab.internal

for dns, edit file /etc/resolv.conf and add lines
nameserver 1.1.1.1
nameserver 2.2.2.2
(where 1.1.1.1 and 2.2.2.2 are your nameservers)

for proxy, use your browser configuration

How do I add a second gateway on higher metric incase the first goes down?

You need to install routed and configure /etc/gateway. Another recommended option is install zebra / Quagga server and configure it. Both allows you to define and configure various routing parameters including metric.

How can I get (in a variable) the current default gateway? Is there a sort of “default gateway enviroment variable” that I can read?
Thanks

Run following to display default gateway:
ip route show | grep default | awk ‘< print $3>‘
Use following to store gateway IP in a variable called GW:
GW=$(ip route show | grep default | awk ‘< print $3>‘)
echo $GW

vivek, many many many thanks. It works!

For two interfaces that both do dhcp the metrics on the default gateway can be added like this.

auto eth1
iface eth1 inet dhcp
metric 10

auto eth2
iface eth2 inet dhcp
metric 20

Is there any way,so that we can give proxy addresss frm command line apart from browser.because if we give this from command line,it will be applicable to all system.

I have two interfaces, eth0 & eth1. eth0 fixed IP 192.168.1.20 hardwired to test machine with fixed IP 192.168.1.6, (not easily altered).
I want eth1 to connect to internet via a DHCP Server Router. Without eth1 enabled there is no problem but as soon as I enable eth1 as DHCP client I lose any access to 192.168.1.6
Have spent many hours altering the route(s), etc., with no success.
Do I have to use ipchains or can it be achieved with route?

I am having some routing problems with Ubuntu 9.04:
Whenever I start up my system, the Internet won’t work unless I do:
«sudo route add default gw 192.168.1.254»
I tried to alter /etc/network/interfaces, but with no luck. After restart, it doesn’t work. executing route prints:

catalin@lolinux:

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 wlan0

After I manually add the gateway, everything is fine, and route prints another gateway:

catalin@lolinux:

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 wlan0
default dsldevice.lan 0.0.0.0 UG 0 0 0 wlan0

Is there any difference from what I altered and the kernel routing table? If there is, how do I modify that? Or would a startup script be a better solution?

I have the “gateway 192.168.1.1” in my network file but I’m still required to manually set the route after reboot. This behavior began only after I “bonded” my two NIC’s. The routing table before the manual route command shows
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 0 0 0 bond0
192.168.1.0 0.0.0.0 255.255.255.0 U 1 0 0 eth1
192.168.1.0 0.0.0.0 255.255.255.0 U 1 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 eth0
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth1
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 bond0
and after adds this one line just below the 169.254… line
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 bond0

Am I missing something or am I experiencing a true bug?

I’m using Kubuntu 9.04 Jaunty.

I am having the same problem..I have to manually set my default gateway after each boot up even though all my network settings include it. How do I get it to stick?

I eventually removed Network Manager. Set everything up manually and it works fine.

I just switched to static ip’s and set everything through wicd..works perfectly. Also I used the network admin tool and I believe that screwed up lots of things.

How can I find Gateway server !? to add the numbers to the address code!?

How can i use 2 gateway , I have a complex network using 2 ISP and Linux as a cache and firewall and a router.

i WANT lINUX router to be able to use both ISP in same time and could nat global IP.

I am using my nanostation 5 as a router… but I can’t receive ping from the ISP gateway… even though I have my ip in the same range. I found this site but the GW isn’t adding… Here are my tables

Destination Gateway Genmask Flags Metric Ref Use Iface
10.64.64.64 * 255.255.255.255 UH 0 0 0 ppp0
10.29.136.0 * 255.255.255.0 U 0 0 0 eth0
169.254.0.0 * 255.255.0.0 U 0 0 0 eth0
default * 0.0.0.0 U 0 0 0 ppp0

My ip range is 10.29.136.0… I need to add 10.29.136.1 as GW

youtr ip 169.254 its not corect. Reset your router

Hehe
funny thing here! very old Debian distro, I’m trying to add new default gateway via.. tun interface (VPN), but it’s refusing to add anything 😀

ip route
10.10.0.2 dev tun0 proto kernel scope link src 10.10.0.1
10.1.0.0/24 via 10.10.0.2 dev tun0
10.0.0.0/16 dev eth1 proto kernel scope link src 10.0.0.254
192.168.0.0/16 dev eth0 proto kernel scope link src 192.168.33.100
default via 192.168.0.1 dev eth0

ping 10.1.0.1
PING 10.1.0.1 (10.1.0.1) 56(84) bytes of data.
64 bytes from 10.1.0.1: icmp_seq=1 ttl=64 time=0.726 ms
64 bytes from 10.1.0.1: icmp_seq=2 ttl=64 time=0.544 ms
64 bytes from 10.1.0.1: icmp_seq=3 ttl=64 time=1.60 ms
64 bytes from 10.1.0.1: icmp_seq=4 ttl=64 time=1.58 ms

sudo ip route add default via 10.1.0.1
RTNETLINK answers: No such process

sudo route add default gw 10.1.0.1
SIOCADDRT: Nie ma takiego procesu

solved, I’ve used 10.10.0.2 as gateway which is IP alias of VPN

add the following to the bottom of your /etc/network/interfaces file

# Static route
up route add -net xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx dev ethX

I use the following commands to add a new gateway and remove an existing one :

sudo route add default gw 192.168.12.1 eth1
sudo route delete default gw 10.0.2.2 eth0

Источник

Ручная настройка сети в Linux

Для доступа к сетевым картам в Linux используются так называемые интерфейсы. Интерфейсы это не файлы устройств и их нет в каталоге /dev. Интерфейсы создаются динамически и не всегда связаны с сетевыми картами. Например интерфейс ppp0 — это интерфейс VPNа, организованного по протоколу PPTP, а интерфейс lo это виртуальная сетевая карта с адресом localhost (127.0.0.1). В Linux имена интерфейсов традиционно состоят из мнемонического типа интерфейса и его порядкового номера. Карты ethernet доступны через интерфейсы eth0, eth1 и т.д. В системах, использующих systemd способ именования другой — интерфейсы имеют имена вида enp2s0 (en -Ethernet, p — PCI, 2 — номер на шине) Список всех интерфейсов можно посмотреть командой ifconfig -a или ip link .

Привязка интерфейса к карте

При наличии нескольких сетевых карт возникает вопрос о порядке их нумерации. В CentOS 6 эта задача возложена на подсистему обнаружения и конфигурации устройств — udev. В системах с systemd правила именования встроены в udev, но могот быть переопределены, как написано ниже.

Конфигурационный файл переименования интерфейсов обновляется автоматически при первом обнаружении очередной сетевой карты и находится в файле /etc/udev/rules.d/70-persistent-net.rules. Файл состоит из строк такого содержания:

Видно, что нумерация опирается на аппаратный (MAC) адрес карты. Если в компьютере заменить карту, то интерфейс eth0 станет недоступным, а новая карта получит имя eth1. Если есть желание вручную назначить имена картам, то можно отредактировать этот файл, выставив желаемые соответствия между MAC адресами именами интерфейсов (возможно потребуется перезагрузка).

ifcfg

Классическая утилита конфигурации сетевых интерфейсов ifcfg

route

Настройка таблицы маршрутизации route

В современных дистрибутивах линукса на смену ifconfig и route приходит универсальная утилита ip

Адреса серверов DNS и имя локального домена вписываются в файл /etc/resolv.conf

Ручная настройка сети в ArchLinux

Для просмотра доступных сетевых интерфейсов используется команда ip link

ArchLinux использует для настройки сети systemd/netctl . Для конфигурации используются файлы профилей, которые хранятся в /etc/netctl/ . В данном каталоге есть подкаталог examples/ из которого можно копировать файлы с образцами профилей в /etc/netctl/ . Например:

Содержимое enp1s0-work после редактирования

Базовые команды netctl

Ручная настройка сети в Ubuntu

Просмотр доступных интерфейсов — ifcfg -a

Файл конфигурации интерфейсов — /etc/network/interfaces . auto — говорит о том, что интерфейс надо конфигурировать при старте системы.

После смены настроек в /etc/network/interfaces , необходимо отключить и снова включить интерфейс.

Ручная настройка сети в CentOS 6

Общие настройки сети

Файл /etc/sysconfig/network используется стартовыми скриптами и содержит ключевые параметры — нужна ли сеть, нужно ли конфигурировать IP v6, имя компьютера. Сюда можно вписать шлюз по умолчанию, но CentOS 6 ориентируется на динамическое подкючение к сетям через WiFi и вписывает его в конфигурацию подходящего интерфейса.

Конфигурация интерфейса

Файлы в каталоге /etc/sysconfig/network-scripts с именами вида ifcfg-eth0

Интерфейс, получающий адрес по DHCP

Дополнительный IP адрес на интерфейсе eth1

Инициализация VLAN на eth1

Настройка DNS

Файл /etc/resolv.conf

Ручная настройка имен хостов файл /etc/hosts

Настройка брандмауэра

Файл /etc/sysconfig/system-config-firewall правила для настройки программой system-config-firewall

Файл /etc/sysconfig/iptables текущие правила, сохраненные на случай перезагрузки.

После ручного изменения правил их можно сохранить командой service iptables save

Источник

Читайте также:  Как записать диск под windows
Оцените статью