Arch linux настройка dhcp

dhcpd (Русский)

dhcpd — реализация DHCP-сервера от Internet Systems Consortium. Может использоваться, к примеру, на машине, играющей роль маршрутизатора в локальной сети.

Contents

Установка

Использование

dhcpd предоставляет два файла юнитов, dhcpd4.service и dhcpd6.service , с помощью которых можно управлять демоном. Демоны запускаются на всех сетевых интерфейсах для IPv4 и IPv6 соответственно. Альтернативный вариант описан в разделе #Запуск на одном сетевом интерфейсе.

Настройка

Присвойте статический адрес IPv4 тому сетевому интерфейсу, для которого вы хотите запустить DHCP-сервер (в примерах будет использоваться eth0 ). Обратите внимание, что у двух различных сетевых интерфейсов на одной машине не должны полностью совпадать первые три октета адреса.

Автоматическое назначение статического IP при загрузке системы описано в статье Настройка сети#Статический IP-адрес.

Стандартный файл настроек, dhcpd.conf , содержит много незакомментированных примеров, поэтому следует переместить его в другое место, например

и создать на его месте новый.

Минимальная конфигурация может выглядеть следующим образом:

Если необходимо выдать фиксированный IP-адрес конкретному устройству, можно также указать настройки для отдельного хоста:

Опция domain-name-servers содержит адреса DNS-серверов, которые передаются клиентам. В данном примере используются публичные DNS-сервера Google. Если в вашей подсети уже есть DNS-серверы (например, предоставленные провайдером), следует указать их. Если на компьютере уже настроен собственный DNS-сервер, то укажите его адрес ( 139.96.30.100 в нашем примере).

Опции subnet-mask и routers содержат маску подсети и список маршрутизаторов в этой подсети, соответственно. В большинстве случаев для небольших сетей подойдет маска 255.255.255.0 , а в качестве маршрутизатора используется та же машина, на которой настроен DHCP-сервер.

Блоки subnet содержат настройки для отдельных подсетей, которые сопоставляются сетевым интерфейсам, на которых запущен dhcpd. В примере определена одна подсеть 139.96.30.0/24 за интерфейсом eth0 , для которой задан диапазон IP-адресов. Подключаемым клиентам будут присваиваться адреса из этого диапазона.

Запуск на одном сетевом интерфейсе

Если ваш компьютер уже является частью одной или нескольких сетей, может возникнуть ситуация, когда адреса будут выдаваться в том числе и компьютерам из другой сети. Это можно исправить либо настройками dhcpd, либо запуском в качестве демона с помощью systemctl.

Настройки dhcpd

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

Файл службы

В «комплекте поставки» dhcpd не предусмотрен юнит для запуска на одном интерфейсе, поэтому придётся создать его самостоятельно. Сначала скопируйте существующую службу:

Затем отредактируйте строку ExecStart, добавив в неё спецификатор интерфейса:

Это юнит-шаблон, который привязывает процесс к определённому интерфейсу, например — dhcpd4@eth0.service . Здесь eth0 — название сетевого интерфейса; узнать интерфейсы вашей системы можно командой ip link .

Использование для PXE

Настройка для PXE выполняется следующими двумя параметрами:

Эти строки можно указать как в блоке subnet , так и в настройках отдельного хоста host . next-server представляет собой адрес TFTP-сервера, а filename — имя образа для загрузки. Подробнее см. PXE.

Источник

dhcpcd

dhcpcd is a DHCP and DHCPv6 client. It is currently the most feature-rich open source DHCP client, see the home page for the full list of features.

Contents

Installation

dhcpcd-ui AUR is a GTK frontend for the dhcpcd daemon, and optionally wpa_supplicant. It features a configuration dialogue and the ability to enter a pass phrase for wireless networks.

Читайте также:  Как разбивать жесткий диск linux

dhcpcd-ui-patched AUR is a patched version of the dhcpcd-ui AUR package. It uses AppIndicator instead of GtkStatusIcon and compiles with gtk3. Has a sharp tray icon when used with KDE.

Running

To start the daemon for all network interfaces, start/enable dhcpcd.service .

To start the daemon for a specific interface alone, start/enable the template unit dhcpcd@interface.service , where interface can be found with Network configuration#Listing network interfaces.

Using the template unit is recommended; see #dhcpcd and systemd network interfaces for details. In either case, you will be assigned a dynamic IP address. To assign a static IP address, see #Static profile.

Configuration

The main configuration is done in /etc/dhcpcd.conf . See dhcpcd.conf(5) for details. Some of the frequently used options are highlighted below.

DHCP static route(s)

If you need to add a static route client-side, add it to /etc/dhcpcd.exit-hook . The example shows a new hook-script which adds a static route to a VPN subnet on 10.11.12.0/24 via a gateway machine at 192.168.192.5 :

You can add multiple routes to this file.

DHCP Client Identifier

The DHCP client may be uniquely identified in different ways by the server:

  1. hostname (or the hostname value sent by the client),
  2. MAC address of the network interface controller through which the connection is being made, linked to this is the third,
  3. Identity Association ID (IAID), which is an abstraction layer to differentiate different use-cases and/or interfaces on a single host,
  4. DHCP Unique Identifier (DUID).

For a further description, see RFC 3315.

It depends on the DHCP-server configuration which options are optional or required to request a DHCP IP lease.

If the dhcpcd default configuration fails to obtain an IP, the following options are available to use in dhcpcd.conf :

  • hostname sends the hostname set in /etc/hostname
  • clientid sends the MAC address as identifier
  • iaid derives the IAID to use for DHCP discovery. It has to be used in an interface block (started by interface , see [1]), but more frequently the next option is used:
  • duid triggers using a combination of DUID and IAID as identifier.

The DUID value is set in /var/lib/dhcpcd/duid . For efficient DHCP lease operation it is important that it is unique for the system and applies to all network interfaces alike, while the IAID represents an identifier for each of the systems’ interfaces (see RFC 4361).

Care must be taken on a network running Dynamic DNS to ensure that all three IDs are unique. If duplicate DUID values are presented to the DNS server, e.g. in the case where a virtual machine has been cloned and the hostname and MAC have been made unique but the DUID has not been changed, then the result will be that as each client with the duplicated DUID requests a lease the server will remove the predecessor from the DNS record.

Static profile

Required settings are explained in Network configuration. These typically include the network interface name, IP address, router address, and name server.

Configure a static profile for dhcpcd in /etc/dhcpcd.conf , for example:

More complicated configurations are possible, for example combining with the arping option. See dhcpcd.conf(5) for details.

Fallback profile

It is possible to configure a static profile within dhcpcd and fall back to it when DHCP lease fails. This is useful particularly for headless machines, where the static profile can be used as «recovery» profile to ensure that it is always possible to connect to the machine.

Читайте также:  Как загружается логотип windows

The following example configures a static_eth0 profile with 192.168.1.23 as IP address, 192.168.1.1 as gateway and name server, and makes this profile fallback for interface eth0 .

Hooks

dhcpcd executes all scripts found in /usr/lib/dhcpcd/dhcpcd-hooks/ in a lexical order. See dhcpcd.conf(5) and dhcpcd-run-hooks(8) for details.

This article or section needs expansion.

10-wpa_supplicant

Enable this hook by creating a symbolic link, which ensures the current version is used, even after package updates:

The 10-wpa_supplicant hook, if enabled, automatically launches wpa_supplicant on wireless interfaces. It is started only if:

  • no wpa_supplicant process is already listening on that interface.
  • a wpa_supplicant configuration file exists. dhcpcd checks

by default, in that order, but a custom path can be set by adding env wpa_supplicant_conf=configuration_file_path into /etc/dhcpcd.conf .

If you manage wireless connections with wpa_supplicant itself, the hook may create unwanted connection events. For example, if you stop wpa_supplicant the hook may bring the interface up again. Also, if you use netctl-auto, wpa_supplicant is started automatically with /run/network/wpa_supplicant_interface.conf for config, so starting it again from the hook is unnecessary and may result in boot-time parse errors of the /etc/wpa_supplicant/wpa_supplicant.conf file, which only contains dummy values in the default packaged version.

To disable the hook remove the symbolic link you added, or add nohook wpa_supplicant to dhcpcd.conf .

Tips and tricks

Speed up DHCP by disabling ARP probing

dhcpcd contains an implementation of a recommendation of the DHCP standard (RFC 2131) to check via ARP if the assigned IP address is really not taken. This seems mostly useless in home networks, so you can save about 5 seconds on every connect by adding the following line to /etc/dhcpcd.conf :

This is equivalent to passing —noarp to dhcpcd , and disables the described ARP probing, speeding up connections to networks with DHCP.

Remove old DHCP lease

The file /var/lib/dhcpcd/interface.lease , where interface is the name of the interface on which you have a lease, contains the actual DHCP lease reply sent by the DHCP server. For a wireless interface, the filename is /var/lib/dhcpcd/interfacessid.lease , where ssid is the name of the wireless network. It is used to determine the last lease from the server, and its mtime attribute is used to determine when it was issued. This last lease information is then used to request the same IP address previously held on a network, if it is available. If you do not want that, simply delete this file.

If the DHCP server still assigns the same IP address, this may happen because it is configured to keep the assignment stable and recognizes the requesting DHCP client id or DUID (see #DHCP Client Identifier). You can test it by stopping dhcpcd and removing or renaming /var/lib/dhcpcd/duid . dhcpcd will generate a new one on next run.

Keep in mind that the DUID is intended as persistent machine identifier across reboots and interfaces. If you are transferring the system to new computer, preserving this file should make it appear as old one.

Different IPs when multi-booting

If you are dualbooting Arch and OS X or Windows and want each to receive different IP addresses, you can exert control about the IPs leased by specifying a different DUID in each operating system installation.

Читайте также:  Apache maven установка linux

In Windows (post XP) the DUID should be stored in the

On OS X it is directly accessible in Network\adapter\dhcp preferences panel .

If you are using a dnsmasq DHCP server, the different DUIDs can be used in appropriate dhcp-host= rules in its configuration.

/etc/resolv.conf

If resolvconf is available DNS information will be sent to it, if not, then dhcpcd itself will write to /etc/resolv.conf .

/etc/resolv.conf overwriting can be stopped by disabling the hook /usr/lib/dhcpcd/dhcpcd-hooks/20-resolv.conf . Do so by adding the following to the last section of /etc/dhcpcd.conf :

Alternatively, you can create a file called /etc/resolv.conf.head containing your DNS servers. dhcpcd will prepend this file to the beginning of /etc/resolv.conf .

Or you can configure dhcpcd to use the same DNS servers every time. To do this, add the following line at the end of your /etc/dhcpcd.conf , where dns-server-ip-addressses is a space separated list of DNS IP addresses.

For example, to set it to Google’s DNS servers:

Troubleshooting

Client ID

If you are on a network with DHCPv4 that filters Client IDs based on MAC addresses, you may need to change the following line:

Else, you may not obtain a lease since the DHCP server may not read your DHCPv6-style Client ID correctly. See RFC 4361 for more information.

Check DHCP problem by releasing IP first

A problem may occur when DHCP gets a wrong IP assignment, such as when two routers are tied together through a VPN. The router that is connected through the VPN may be assigning IP address. To fix it, as root, release the IP address:

Then request a new one:

You may have to run those two commands many times.

Problems with noncompliant routers

For some (noncompliant) routers, you will not be able to connect properly unless you comment the line

in /etc/dhcpcd.conf . This should not cause issues unless you have multiple DHCP servers on your network (not typical); see this page for more information.

dhcpcd and systemd network interfaces

dhcpcd.service can be enabled without specifying an interface. This may, however, create a race condition at boot with systemd-udevd trying to apply a predictable network interface name:

To avoid it, enable dhcpcd per interface it should bind to as described in #Running. The downside of the template unit is, however, that it does not support hot-plugging of a wired connection and will fail if the network cable is not connected. To work-around the failure, see #Timeout delay.

It is also possible to use denyinterfaces or allowinterfaces in dhcpcd.conf(5) to stop dhcpcd from binding to kernel names, for example

Timeout delay

If dhcpcd operates on a single interface and fails to obtain a lease after 30 seconds (for example when the server is not ready or the cable not plugged), it will exit with an error.

To have dhcpcd wait indefinitely for one-time, edit the unit and set the timeout option to 0 :

To have it wait indefinitely, let the unit restart after it exited:

Known issues

dhcpcd@.service causes slow startup

By default the dhcpcd@.service waits to get an IP address before forking into the background via the -w flag for dhcpcd. If the unit is enabled, this may cause the boot to wait for an IP address before continuing. To fix this, create a drop-in file for the unit with the following:

Источник

Оцените статью