Настройка сети в Linux: шаг за шагом руководство

Sprintbox - сетевые интерфейсы

1.0 Введение

Ethernet-Howto содержит детальную информацию об уровне поддержки ОС GNU/Linux
большинства доступных ethernet сетевых карт. Документ рассказывает
об основных вопросах конфигурации и вопросах, связанных с выбором
подходящего драйвера, а также последующей установке этого драйвера,
его настройке и использовании. Здесь вы не найдете информации о
дальнейших этапах настройки (выбор сетевого адреса, маршрутизация и т. д.).
Эта информация может быть найдена в разнообразной Linux документации.

На заре развития linux, устаревшие на данный момент ISA ethernet
сетевые карты были нормой. ISA шина не давала представления linux
о том, какие сетевые карты установлены и какие настройки поддерживает
каждая из них. Конечным пользователям было сложно разобраться с этой
проблемой и они обращались к данному руководству, чтобы облегчить себе жизнь.

К счастью, PCI шина теперь есть почти в каждом современном компьютере,
а ISA шина осталась на обочине глотать пыль вместе с 386 и 486 компьютерами.
Разработчики PCI шины распознали проблему с определением
сетевых карт на ISA шине и добавили PCI картам возможность сообщать
компьютеру своего производителя и модель, а также те настройки, которые
могут быть использованы.

Безвременная кончина ISA шины радикально уменьшила количество проблем для
конечнного пользователя. В принципе, большинству сегодняшних пользователей
linux нет нужды обращаться к этому руководству за помощью. Как бы то ни было,
всегда существуют случаи, когда что-то работает не так, как ожидалось, иногда
для решения проблемы требуется подсказка. И наконец, до сих пор существуют
компьютеры с ISA шиной, преданно работающие в глубине темных чуланов.

Эта версия документа охватывает ethernet драйвера, поддерживаемые ядром
вплоть до версии 2.4.21 включительно. Также были отмечены некоторые
особенности грядущего релиза версии 2.6.

  • Paul Gortmaker, p_gortmaker @ yahoo.com
  • Donald J. Becker, becker @ scyld.com

Права на этот документ: Copyright (c) 1993-2003 by Paul Gortmaker
Да, я веду этот проект уже в течение 10 лет!
Пожалуйста прочитайте Disclaimer и информацию о копировании ()
в конце этого документа для получения сведений о том как переиздавать
этот документ и привычного ‘мы не несем ответственности за то, что вы ухитритесь
сломать…’ правового содержания.

2.4.1 Драйвер в качестве модуля

Настроить драйвера ISA карт таким образом достаточно сложно, вам
потребуется разбираться с базовым адресом ввода/вывода
сетевой карты, чтобы модуль знал где ее искать. Эта информация
хранится в файле /etc/modules.conf.

К примеру, возьмем пользователя у которого две ISA сетевые карты
NE2000, одна по адресу 0x300, другая 0x240. Чтобы все
это заработало, в файл /etc/modules.conf нужно добавить
следующие строки:

alias eth0 nealias eth1 neoptions ne io=0x240,0x300

Указанные выше строки можно прокомментировать следующим образом:
Если администратор (или ядро) скажет modprobe eth0 или
modprobe eth1, для интерфейса eth0 или eth1 должен
быть загружен драйвер с именем ne.o. Более того, когда модуль
с именем ne.o будет загружен, он будет знать где искать
сетевые карты (io=0x240,0x300). Отметим, что префикс 0x
важен, так как часто используемые в мире DOS записи типа 300h
не будут работать. Порядок записи адресов ввода/вывода имеет значение,
так как именно на нем основывается отождествление имени интерфейса
с физическим воплощением сетевой картой.

Большинство драйверов ISA сетевых карт, работая как модули, могут принимать
разделенные запятой значения адресов ввода/вывода и таким образом
управлять несколькими картами. Тем не менее, некоторые (еще более старые?)
драйвера, такие как 3c501.o модуль, могут контроллировать только одну
карту на загруженный модуль. В этом случае, для того чтобы
распознать обе сетевые карты, вы можете загрузить модуль дважды.
Тогда файл /etc/modules.conf будет иметь следующий вид:

alias eth0 3c501alias eth1 3c501options eth0 -o 3c501-0 io=0x280 irq=5options eth1 -o 3c501-1 io=0x300 irq=7

В этом примере опция -o указывает на то, что необходимо
каждой копии модуля дать уникальное имя, так как невозможно
использовать два модуля с одинаковыми именами. Опция irq=
была использована для указания уникального номера канала прерывания
для каждой сетевой карты. (Этот метод также применим при
использовании модулей, понимающих адреса ввода/вывода, перечисленные
через запятую, но подход будет менее эффективен, так как
модуль будет загружен дважды, хотя он в этом и не нуждается.)

В качестве завершающего примера, возьмем пользователя с двумя
картами, одной 3c503 и адресом 0x350, а другой
SMC Elite16 (wd8013) и адресом 0x280.
В результате:

alias eth0 wdalias eth1 3c503options wd io=0x280options 3c503 io=0x350

Для PCI сетевых карт вам скорее всего потребуется указать
только alias строки для того, чтобы установить соотношение
между ethN интерфейсом и конкретным именем драйвера.
Адреса ввода/вывода у PCI карт распознаются без проблем.

Доступные модули обычно хранятся в /lib/modules/`uname -r`/net,
где uname -r команда, определяющая версию ядра (пример: 2.0.34).
Вы можете ознакомиться с содержимым этого каталога и найти
подходящий для вашей сетевой карты драйвер. Один раз по-человечески
настроив modules.conf, вы сможете тестировать все используя:

modprobe eth0modprobe eth1...modprobe ethN-1

где ‘N’ — это количество ваших ethernet сетевых интерфейсов.
Отметим, что имя интерфейса (ethX), устанавливаемое для драйвера ядром
не зависит от имени, использованного в alias строке.
Для более детального знакомства с проблемой почитайте:
(не входит в данную версию перевода документа)

INET6 ADDRESS FAMILY

The auto Method

rdnssd

Options

privext int
Privacy extensions (RFC4941) (0=off, 1=assign, 2=prefer)
accept_ra int
Accept router advertisements (0=off, 1=on, 2=on+forwarding). Default value: «2»
dhcp int
Use stateless DHCPv6 (0=off, 1=on)
request_prefix int
Request a prefix through DHCPv6 Prefix Delegation (0=off, 1=on). Default value: «0»
ll-attempts
Number of attempts to wait for a link-local address. Default value: «60»
ll-interval
Link-local address polling interval in seconds. Default value: «0.1»

Options

(No options)

The static Method

Options

address address
Address (colon delimited/netmask) required
netmask mask
Netmask (number of bits, eg 64) deprecated
metric metric
Routing metric for default gateway (integer)
gateway address
Default gateway (colon delimited)
media type
Medium type, driver dependent
hwaddress address
Hardware address or «random»
mtu size
MTU size
accept_ra int
Accept router advertisements (0=off, 1=on, 2=on+forwarding)
autoconf int
Perform stateless autoconfiguration (0=off, 1=on). Default value: «0»
privext int
Privacy extensions (RFC3041) (0=off, 1=assign, 2=prefer)
scope
Address validity scope. Possible values: global, site, link, host
preferred-lifetime int
Time that address remains preferred
dad-attempts
Number of attempts to settle DAD (0 to disable DAD). Default value: «60»
dad-interval
DAD state polling interval in seconds. Default value: «0.1»

updown

Options

hwaddress address
Hardware address or «random»
mtu size
MTU size

The dhcp Method

Options

hwaddress address
Hardware address or «random»
accept_ra int
Accept router advertisements (0=off, 1=on, 2=on+forwarding). Default value: «1»
autoconf int
Perform stateless autoconfiguration (0=off, 1=on)
request_prefix int
Request a prefix through DHCPv6 Prefix Delegation (0=off, 1=on). Default value: «0»
ll-attempts
Number of attempts to wait for a link-local address. Default value: «60»
ll-interval
Link-local address polling interval in seconds. Default value: «0.1»

The v4tunnel Method

ipiproute

Options

address address
Address (colon delimited/netmask) required
netmask mask
Netmask (number of bits, eg 64) deprecated
endpoint address
Address of other tunnel endpoint (IPv4 dotted quad) required
local address
Address of the local endpoint (IPv4 dotted quad)
metric metric
Routing metric for default gateway (integer)
gateway address
Default gateway (colon delimited)
ttl time
TTL setting
mtu size
MTU size
preferred-lifetime int
Time that address remains preferred

The 6to4 Method

ipiproute

Options

local address
Address of the local endpoint (IPv4 dotted quad) required
metric metric
Routing metric for default gateway (integer)
ttl time
TTL setting
mtu size
MTU size
preferred-lifetime int
Time that address remains preferred

2.1 Как я скажу Linux о том, какой драйвер использовать?

В большинстве GNU/Linux дистрибутивов драйверы представлены в виде
загружаемых модулей, ими являются небольшие двоичные файлы,
которые сливаются с операционной системой во время ее работы.
Модуль дает операционной системе (ядру) информацию о том как
управлять конкретной ethernet сетевой картой. В этом документе,
указано имя модуля для каждой сетевой карты, эти данные находятся
в специальном разделе. Узнав имя модуля, вам потребуется добавить
его в файл /etc/modules.conf, так Linux узнает какой
модуль нужно загрузить для вашей сетевой карты. Синтаксис
команды, которую следует добавить в /etc/modules.conf
похож на указанный ниже.

alias eth0 module_nameoptions module_name option1=value1 option2=value2 ...

Строка опций обычно требуется только для старого аппаратного
обеспечения на базе шины ISA. Для систем с несколькими
сетевыми картами чаще всего нужно использовать дополнительные
строки c именами интерфейсов eth1, eth2 и т. д.

Модули обычно проживают в каталоге /lib/modules/,
который далее ветвится согласно версии ядра (uname -r)
и подсистеме (в нашем случае, net). Эти файлы
кладутся сюда разработчиком дистрибутива или пользователем,
когда после создания своего собственного
ядра и модулей он говорит make modules_install
(см. kernel howto для получения более детальной
информации по этому вопросу).

Если вы создаете свое собственное ядро, вместо
использования отдельных файлов, можно встроить все
драйвера непосредственно в ядро. В этом случае, драйверы
будут распознавать аппаратное обеспечение при загрузке
операционной системы. Передача опций для драйверов поддерживается
командной строкой ядра, появление которой предшествует
загрузке системы (см. BootPrompt Howto для получения
более детальной информации по этому вопросу). Пользователь
выбирает какие драйвера использовать при выполнении
команды make config (опять же, за деталями
обращайтесь к kernel howto).

INTERFACE SELECTION

ifup-aifup

Lines beginning with «allow-» are used to identify interfaces that should
be brought up automatically by various subsystems. This may be done using
a command such as «ifup —allow=hotplug eth0 eth1», which will only bring
up eth0 or eth1 if it is listed in an «allow-hotplug» line. Note that
«allow-auto» and «auto» are synonyms.
(Interfaces marked «allow-hotplug» are brought up when udev detects them.
This can either be during boot if the interface is already present, or at a later time,
for example when plugging in a USB network card.
Please note that this does not have anything to do with detecting a network cable being plugged in.)

Lines beginning with «no-auto-down» are used to identify interfaces that should
not be brought down by the command «ifdown -a». Its main use is to prevent an
interface from being brought down during system shutdown time, for example if
the root filesystem is a network filesystem and the interface should stay up
until the very end. Note that you can still bring down the interface by
specifying the interface name explicitly.

Lines beginning with «no-scripts» are used to identify interfaces for which scripts in
/etc/network/if-*.d/

should not be run when those interfaces are brought up or down.
he above will match eth0 and eth1, and will bring up both interfaces using the «iface eth» stanza.

Советы и рекомендации

Объединение сетевых интерфейсов (bonding) или LAG

Бондинг — объединение нескольких сетевых интерфейсов в одно логическое устройство. См. статьи , и Wireless bonding.

Псевдонимы для IP-адресов

Псевдонимы (aliases) необходимы для назначения нескольких IP-адресов одному сетевому интерфейсу. Благодаря этому один узел сети может иметь несколько подключений, каждое из которых будет использоваться для конкретной цели. Типичное применение этой возможности — виртуальный хостинг Web- и FTP-серверов или реорганизация серверов без необходимости обновления каких-либо других машин (особенно полезно для серверов имен).

Пример

Чтобы вручную назначить псевдоним для определенного сетевого интерфейса (например, ) используйте утилиту ip из пакета :

# ip addr add 192.168.2.101/24 dev enp2s0 label enp2s0:1

Для удаления псевдонима выполните:

# ip addr del 192.168.2.101/24 dev enp2s0:1

По умолчанию для исходящих из определённой подсети пакетов используется основной псевдоним устройства. Если же отправитель находится в подсети вторичного псевдонима, то IP-адрес отправителя в заголовке пакета будет соответствующим. В случае наличия более чем одного сетевого интерфейса маршруты по умолчанию можно узнать командой .

Promiscuous mode

Promiscuous mode («неразборчивый» режим) предполагает, что (беспроводной) сетевой интерфейс перенаправляет весь входящий трафик ядру операционной системы для дальнейшей обработки. Это противоположность «нормальному» режиму, при котором интерфейс отбрасывает пакеты, которые не ожидались быть полученными. Чаще всего эта возможность используется для решения сетевых проблем и анализа пакетов.

/etc/systemd/system/[email protected]
Description=Set %i interface in promiscuous mode
After=network.target


Type=oneshot
ExecStart=/usr/bin/ip link set dev %i promisc on
RemainAfterExit=yes


WantedBy=multi-user.target

Чтобы включить «неразборчивый» режим для интерфейса , включите .

Получение информации о сокетах

Примеры использования:

Показать все TCP-сокеты с названиями сервисов:

$ ss -at

Показать все TCP-сокеты с номерами портов:

$ ss -atn

Показать все UDP-сокеты:

$ ss -au

За подробной информацией обращайтесь к справочной странице .

КОМАНДА MTR В СИСТЕМАХ LINUX

MTR (Matt’s traceroute) — это программа с интерфейсом командной строки, которая служит средством диагностики сети и устранения неполадок. Данная  команда сочетает в себе функциональность ping и traceroute. Как и traceroute, команда mtr покажет маршрут от компьютера до указанного хоста в сети. mtr предоставляет множество статистических данных о каждом прыжке, например время отклика и процент. С помощью команды mtr вы получите больше информации о маршруте и сможете увидеть проблемные устройства по пути. Если вы видите внезапное увеличение времени ответа или потерю пакетов, то очевидно, что где-то плохой канал.

Синтаксис команды MTR следующий:

mtr <опции> hostname/IP

Команда mtr без опций показывает статистику, включая каждый прыжок (имена хостов) со временем и % потерь

# mtr google.com

Вывод команды mtr

Используем опцию -g и получим IP-адреса вместо имен хостов:

# mtr -g google.com

Показать числовые IP-адреса и имена хостов:

# mtr -b google.com

Установить количество пингов, которые вы хотите отправить:

# mtr -c 10 google.com

Получите отчет о mtrрезультате выполнения команды:

# mtr -r -c 10 google.com > mtr-output.log

или же с флагом -w (обеспечивает более подробный вывод):

# mtr -rw -c 10 google.com > mtr-output-advanced.log

Принудительно использовать TCP вместо ICMP:

# mtr –tcp google.com

Принудительно использовать UDP вместо ICMP:

# mtr –udp google.com

Чтобы указать максимальное количество переходов (по умолчанию — 30) между локальной системой и удаленной машиной:

# mtr -m 35 google.com

Определить размер пакета:

Предотвращение дублирования сетевых адресов

Для предотвращения дублирования сетевых адресов, присваиваемых сетевым интерфейсам, NetworkManager использует параметр сетевого интерфейса ipv4.dad-timeout. 

Значения этого параметра:

  • любое положительное число — периодичность проверки в миллисекундах. При положительном значении параметра при смене адреса при активации интерфейса выполняется проверка дублирования. Проверка выполняется с заданной периодичностью. Активация интерфейса не завершается  успехом без успешного завершения проверки (т.е., до обнаружения, что дублирование отсутствует).

  • 0 — проверка не выполняется.
  • -1 — применяется по умолчанию в обновлениях Astra Linux, выпущенных до обновления БЮЛЛЕТЕНЬ № 2023-1023SE17 (оперативное обновление 1.7.5). Указывает, что используется значение 0 (проверка не выполняется).
  • 2222 — применяется по умолчанию начиная с обновления Astra Linux, выпущенных до обновления БЮЛЛЕТЕНЬ № 2023-1023SE17 (оперативное обновление 1.7.5). Задает интервал проверки 2222 миллисекунды.

Иное значение, применяемое по умолчанию, может быть задано в секции . Для задания значения в конфигурационном файле отдельного сетевого интерфейса параметр можно разместить в секции :

dad-timeout=<значение>
ipv4.dad-timeout=<значение>

sudo nmcli con mod <имя_соединения> ipv4.dad-timeout <значение>

sudo nmcli con mod Проводное\ соединение\ 1 ipv4.dad-timeout -1

Networking: Настройка сети из командной строки

Теоретически, службы NetworkManager и networking конфликтовать не должны, так как первая не работает с сетевыми интерфейсами, перечисленными в файле /etc/network/interfaces, а вторая — работает только с интерфейсами, перечисленными в этом файле, но при переходе к использованию службы networking лучше , для чего выполнить команду:

sudo systemctl —now mask NetworkManager

Традиционно, настройка сети TCP/IP из командной строки выполняется с использованием инструментов ifup и ifdown, входящих в пакет ifupdown, и предназначенных для высокоуровневой настройки сети.При этом можно выделить два типичных случая

  • Для систем, работающих в статичной сети (например, для серверов), следует сохранять как можно более простую конфигурацию ;
  • Для систем, работающих с динамически меняющимися сетями и IP-адресами (например, для мобильных компьютеров) рекомендуется дополнительно использовать для настройки пакет  resolvconf, упрощающий переключение конфигураций при смене сетевого адреса.

Пакет ifupdown содержит три команды: команды ifup и ifdown, обеспечивающие настройки сетевых интерфейсов в соответствии с конфигурационным файлом /etc/network/interfaces, и команда ifquery, проверяющая корректность конфигурационного файла /etc/network/interfaces. При этом список включенных в данный момент интерфейсов хранится в файле /run/network/ifstate

Сценарий изменения настройки сетевого интерфейса (на примере интерфейса eth0):

  • Внести изменения в файл /etc/network/interfaces в секцию, относящуюся к интерфейсу eth0.

  • Проверить корректность файла:

    sudo ifquery eth0

  • Перезапустить интерфейс. Лучше всегда делать это одной командой, чтобы не потерять машину при работе через удалённое подключение:

    sudo ifdown eth0; sudo ifup eth0

Типичной ошибкой при использовании команд ifdown/ifup является  повторное назначение параметров интерфейса неотключенным и некорректно работающим сервисом NetworkManager,что выглядит как игнорирование изменений, внесённых в файл /etc/network/interfaces.Для проверки полного состояния сетевого интерфейса вместо устаревшей команды ifconfig следует использовать современную команду ip из пакета iproute2:

  • проверить все сетевые адреса, назначенные сетевому интерфейсу:

    ip address show dev eth0

  • очистить все сетевые адреса, назначенные сетевому интерфейсу:

    sudo ip address flush dev eth0

How to set the MTU (Max transfer unit / packet size) with VLANS over a bonded interface

MTU needs to be configured on the bonding interface and slave interfaces after the reset of the configuration has been applied to the bonding interfaces. This is done using a post-up line in the bonding interface configuration.

auto bond0
iface bond0 inet manual
        up ifconfig lacptrunk0 0.0.0.0 up
        slaves eth0 eth1
# bond-mode 4 = 802.3ad
        bond-mode 4
        bond-miimon 100
        bond-downdelay 200
        bond-updelay 200
        bond-lacp-rate 1
        bond-xmit-hash-policy layer2+3
        post-up ifconfig eth0 mtu 9000 && ifconfig eth1 mtu 9000 && ifconfig bond0 mtu 9000

#vlan devices will use the MTU set on bond0 device
auto vlan101
iface vlan101 inet static

        address 10.101.60.123/24
        gateway 10.155.60.1
        vlan-raw-device bond0

auto vlan151
iface vlan151 inet static

        address 192.168.1.1/24
        vlan-raw-device bond0

Multiple IP addresses on one Interface

Interface aliasing allows one interface to have multiple IP addresses. This is useful when more than one server is to be visible via the Internet. Note that virtual hosts can support multiple Apache servers with a single IP address. Apache responds to the domain name supplied by the client in the HTTP header. In many other situations, one external IP is needed for each server using a port.

Determining Network Interface Names

ethtool works against specific network interface names like ens160 or eth0. To use it effectively, you first need to determine what names match your physical ports, VLANs, bridges, bonds, or virtual interfaces.

The naming convention varies by Linux distro and kernel version. Some examples:

  • ETH0 – Classic ethX style name associated with physical ports
  • ENS – Newer consistent naming scheme like ens160 or ens5
  • ENO/ENP – Naming scheme for on-board adapters like eno1
  • VXLAN/BR – Virtual interfaces like vxlan0 or bridge interfaces

To find your current interfaces, use :

This shows a physical interface , a bonded port , and the bond interface itself .

You can now pass these names into ethtool for interrogation.

Setting the speed and duplex

Autonegotiation repeatedly failing is often a symptom of faulty cabling, so investigate physical matters before assuming that the interfaces’ autonegotiation algorithms are incompatible. If you turn off autonegotiation and set speed and duplex manually then the partner interface at the other end of the cable will assume that the absence of autonegotiation indicates a speed of 10Mbps and a duplex of half. For error-free operation if you set speed and duplex manually you must ensure that exactly the same speed and duplex are configured on the partner interface.

If you set your interface’s speed and duplex by hand, then some trial and error may be required. Here are the basic steps:

  • Install the ethtool and net-tools packages, so that you have the ethtool and mii-tool programs. One or both of these might work for your interface.

  • Make sure you have a way to login to the system in case the network interface becomes nonfunctional. An SSH connection could be disrupted, so you should have a fallback strategy.

  • Identify the interface in question (it will often be eth0). Adjust the remainder of these instructions accordingly.
  • Try to determine what its current speed and duplex settings are. This is where it gets fun:
    • As root, try ethtool eth0 first, and see whether the «Speed:» and «Duplex:» lines look valid. If not, the ethtool may not be supported by your device.

    • As root, try mii-tool -v eth0 and see whether its output looks correct. If not, them mii-tool may not be supported by your device.

    • If neither one is supported, you may have to set parameters directly on the kernel driver module. Identify which driver module you’re using by reading the output of dmesg and lsmod. You can then try modinfo MODULENAME to see what parameters it accepts, if any. (You can use modinfo even on modules that are not loaded, for comparison.) ToDo: where does one set kernel module parameters?

  • Next, try to change the settings of the interface while it’s operating. You’ll need to be root, of course. Either:
    • ethtool -s eth0 speed 100 duplex full autoneg off (assuming 100 Mbps and full duplex)

    • mii-tool -F 100baseTx-FD eth0 (same assumption)

    In each case, re-check to see whether the interface settings actually changed, and then try sending some data in and out of the system to see whether the NIC is operating correctly.

  • If one of these commands successfully set your NIC, then you can put it into /etc/network/interfaces so it runs when you bring the interface up (e.g. at boot time). However, before you do that, you should understand that some drivers and devices behave differently than others. When the driver module is loaded, the NIC may begin autonegotiation without any way to stop it (particularly with drivers that do not accept parameters). The settings from interfaces are applied at some point after that, which may be right in the middle of the negotiation. So, some people find it necessary to delay the ethtool or mii-tool command by a few seconds. Thus:

     iface eth0 inet static
            address .../...
            gateway ...
            up sleep 5; ethtool -s eth0 ...

    Or the analogous mii-tool command.

  • Reboot the machine to make sure it comes up correctly, and be prepared to intervene manually (e.g. Ctrl-Alt-Del and then boot into single-user mode from GRUB or LILO) if things don’t work.

Using systemd-resolved for DNS resolution

systemd-resolved is not installed by default but you can use it it runs a local caching dns resolver that can intergrate with ?NetowrkManager and Systemd-network

apt install systemd-resolved

Enabling systemd-resolved

By default it does not get enabled so you need to switch over to use it.

systemctl enable systemd-resolved
ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

Also for glibc apps using nss you need to edit the /etc/nsswitch.conf file so the hosts line reads as follows. This will use man nss-resolve for resolution.

 hosts:           mymachines resolve  files dns myhostname 

Note that resolved supports /etc/hosts so should to go before the files entry.

Checking the status and flushing the cache in systemd-resolved

You can check the status using man resolvectl

resolvectl

You can flush the cache that resolved has with the following

resolvectl flush-cache

Managing systemd-resolved settings

General settings for systemd-resolved are managed in /etc/systemd/resolved.conf see man resolved.conf for more info.

IFACE OPTIONS

pre-up command
Run
command
before bringing the interface up.
If this command fails then
ifup
aborts,
refraining from marking the interface as configured,
prints an error message,
and exits with status 0.
This behavior may change in the future.
up command
post-up command
Run
command
after bringing the interface up.
If this command fails then
ifup
aborts,
refraining from marking the interface as configured
(even though it has really been configured),
prints an error message,
and exits with status 0.
This behavior may change in the future.
down command
pre-down command
Run
command
before taking the interface down.
If this command fails then
ifdown
aborts,
marks the interface as deconfigured
(even though it has not really been deconfigured),
and exits with status 0.
This behavior may change in the future.
post-down command
Run
command
after taking the interface down.
If this command fails then
ifdown
aborts,
marks the interface as deconfigured,
and exits with status 0.
This behavior may change in the future.

There exists for each of the above mentioned options a directory
/etc/network/if-<option>.d/
the scripts in which are run (with no arguments) using
run-parts(8)
after the option itself has been processed.

All of these commands have access to the following environment variables.

IFACE
physical name of the interface being processed
LOGICAL
logical name of the interface being processed
ADDRFAM
address family of the interface
METHOD
method of the interface (e.g.,
static)
MODE
start if run from ifup, stop if run from ifdown
PHASE
as per MODE, but with finer granularity, distinguishing the
pre-up, post-up, pre-down and post-down phases.
VERBOSITY
indicates whether —verbose was used; set to 1 if so, 0 if not.
PATH

the command search path:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

iproute2 method

Also, ifupdown supports specifying multiple interfaces by repeating iface sections with the same interface name. The key difference from the method described above is that all such sections are treated by ifupdown as just one interface, so user can’t add or remove them individually. However, up/down commands, as well as scripts, are called for every section as it used to be.

Note however that this method is dangerous! Certain driver/hardware combinations may sometimes fail to bring the link up if no labels are assigned to the alias interfaces. (Seen this on Debian Wheezy and Jessie with RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 01) auto-negotiating to 10/full. A similar warning from another person exists in the history of this page.)

This /etc/network/interfaces text assigns three IP addresses to eth0.

auto eth0
allow-hotplug eth0
iface eth0 inet static
    address 192.168.1.42/24
    gateway 192.168.1.1

iface eth0 inet static
    address 192.168.1.43/24

iface eth0 inet static
    address 192.168.1.44/24

# adding IP addresses from different subnets is also possible
iface eth0 inet static
    address 10.10.10.14/24

Manual approach:

auto eth0
allow-hotplug eth0
iface eth0 inet static
    address 192.168.1.42/24
    gateway 192.168.1.1
    up   ip addr add 192.168.1.43/24 dev $IFACE label $IFACE:0
    down ip addr del 192.168.1.43/24 dev $IFACE label $IFACE:0
    up   ip addr add 192.168.1.44/24 dev $IFACE label $IFACE:1
    down ip addr del 192.168.1.44/24 dev $IFACE label $IFACE:1
    up   ip addr add 10.10.10.14/24 dev $IFACE label $IFACE:2
    down ip addr del 10.10.10.14/24 dev $IFACE label $IFACE:2

CategoryNetwork CategorySystemAdministration CategoryNetwork

How to Configure Network Interface Using /etc/network/interfaces

Before going into the configuration details, let’s get familiar with the syntax of the /etc/network/interfaces file. We’ll understand some keywords so that we can configure the network correctly.

4.1. The /etc/network/interfaces File Syntax

To enable a network interface at boot time automatically, we use the following syntax:

Here, <interface> is the network interface name, like, eth0.

We declare a network interface with the keyword iface:

The lo stands for loopback, a virtual network interface for local usage, and inet means internet protocol family (IPv4). In short, we assign a special IP address (127.0.0.1).

Here’s the format for the declaration of an interface:

For example, we could declare an interface eth0 and get an IP address dynamically using DHCP:

To configure an interface statically, we follow these steps. First, we define the interface eth1 as a static:

After that, we set the IP address, network mask, and gateway:

To configure the DNS servers, we add:

Here’s a way to define an interface manually without giving it an IP address:

To be able to execute a command or a script after enabling the interface, we use:

We can also run a command or a script before enabling the network interface:

In the same vein, we can use pre-down and post-down options. We run the command before taking the interface down:

Here’s how we can execute a command after taking the interface down:

4.3. Static Configuration

To set up a static IP address to the eth0 interface, let’s first replace the line iface eth0 inet dhcp from earlier:

Then, we give our interface an IP address:

We can add more options, as we’ll see later.

4.4. Enabling and Disabling Network Interfaces

To manually activate or deactivate a network interface, we use ifup/ifdown commands. It’s necessary to have super-user privileges to execute these commands.

In order to enable the interface eth0, for example, we do:

In the same way, we can disable the network interface eth0:

4.5. Full Example Configuration

Now, we will see a complete example of the static configuration step by step.

For this purpose, we open the /etc/network/interfaces file with a text editor like vi :

First, we enable the network interface eth0 at boot time.

Secondly, we set a static IP address, network, and gateway.

Next, we add two DNS servers.

In addition, we put a script to launch a firewall before starting the interface.

Lastly, we add a script to execute a backup after disabling the interface:

Finally, we disable and enable the network interface for changes to take effect:

To configure a secondary interface, we just have to repeat the same steps we saw previously.

DHCP Client Configuration

Setting additional DNS Servers

Example: dhclient3 uses /etc/dhcp/dhclient.conf. The setting you want is:

supersede domain-name-servers 12.34.56.78, 12.34.56.79;

or perhaps

prepend domain-name-servers 12.34.56.78, 12.34.56.79;

Setting additional search domains

Adding search domains for VPNs or local virtual networks:

append domain-name " virt vpn";

Note the leading space since the string is literally appended to the search domain provided by other configurations.

See the dhclient.conf(5) manual page for details.

Bridging

Bridging puts multiple interfaces into the same network segment. This is very popular when connecting a server to multiple switches for high availability or with virtualization. In the latter case it is usually used to create a bridge in the host (eg. dom0) and put the virtual interfaces of the guests (domU) into the bridge.

The bridge-utils package is required to create bridged interfaces.

Example: Connect a server to 2 switches (via eth0 and eth1) by defining bridge 0 and give the server an IP address in this subnet:

auto br0
iface br0 inet static
        address 10.10.0.15/24
        gateway 10.10.0.1
        bridge_ports eth0 eth1
        up /usr/sbin/brctl stp br0 on

If a server is connected to multiple switches then you usually need to run the spanning tree protocol to avoid loops. Therefore STP must be turned on via an «up» command as shown above.

Example: Bridge setup without IP address configuration (use «manual» instead of «static») to «forward» an interface to a guest VM. (The static bridge config contains only 1 physical interface. The virtual interface will be added to the bridge when the VM is started.)

auto br1
iface br1 inet manual
        bridge_ports eth4
        up /usr/sbin/brctl setageing br1 0
        up /usr/sbin/brctl stp br1 off

Note: The Linux bridge supports only STP, no RSTP (Rapid Spanning Tree). Therefore it supports only the old STP Costs, not the new RSTP Costs (see ). This is usually fine with Cisco Switches, but eg. Juniper switches use the RSTP costs and therefore this may lead to different spanning tree calculations and loop problems. This can be fixed by settings the costs manually, either on the switch or on the server. Setting the cost on the switch is preferred as Linux switches back to the default costs whenever an interface does down/up.

How to change network interface name to eth0?

If you ever interested in changing interface name to eth0, then this is the tutorial for you. Use the ip a command to see the network interfaces. As you can see in the below output of ip a command, my Debian system is having a network adapter called enp0s3.

How does the Ethernet interface work in Debian?

The next line demonstrates this for the Ethernet interface /dev/eth0 (similar to line 8 of listing 1). In order to communicate with other computers in a network an interface is assigned an IP address. This address is obtained either dynamically (via DHCP) or set in a fixed way (static configuration).

Why is my eth0 not up at startup?

Note that “allow-auto” and “auto” are synonyms. Please check that it is not disabled in the networking-scripts configs. Do this: See if ONBOOT=”yes”. If it says “no” then it is disabled at startup. Ip address is not static set and won’t change after reboot.

Понравилась статья? Поделиться с друзьями: