- Настройка DHCP-сервера в Linux
- Как работает DHCP?
- Шаг 1: Установка DHCP-сервера
- Шаг 2: Настройка DHCP-сервера
- Шаг 3: Настройка статических IP-адресов для машин клиентов
- Шаг 4: Настройка машин клиентов
- How to Install a DHCP Server in Ubuntu and Debian
- How Does DHCP Work?
- Testing Environment Setup
- Step 1: Installing DHCP Server in Ubuntu
- Step 2: Configuring DHCP Server in Ubuntu
- Step 3: Configure Static IP on DHCP Client Machine
- Step 4: Configuring DHCP Client Machines
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Ubuntu Documentation
- Dynamic Host Configuration Protocol (DHCP)
- Installation
- Configuration
- Linux DHCP Server Configuration
Настройка DHCP-сервера в Linux
Протокол динамической конфигурации узлов (Dynamic Host Configuration Protocol, DHCP) — это сетевой протокол, используемый для автоматического получения узлами IP-адресов и сетевой конфигурации с сервера.
IP-адрес, выделенный DHCP-клиенту DHCP-сервером, находится в «аренде», время аренды может отличаться в зависимости от того, сколько времени клиенту требуется соединение или конфигурация DHCP.
Как работает DHCP?
- После загрузки подключенный к сети клиент (на котором настроено использование DHCP) отправляет DHCP-серверу пакет DHCPDISCOVER.
- Получив пакет запроса DHCPDISCOVER, DHCP-сервер отвечает пакетом DHCPOFFER.
- Клиент принимает пакет DHCPOFFER и отправляет серверу пакет DHCPREQUEST, подтверждая готовность принять сетевую конфигурацию, предоставленную в пакете.
- Получив от клиента пакет DHCPREQUEST, сервер отправляет пакет DHCPACK, который разрешает клиенту использование выделенного IP-адреса.
В данном руководстве мы рассмотрим настройку DHCP-сервера в Ubuntu/Debian Linux, но большенство настроек будет работать и в других дистрибутивах. Для получения административных привилегий все команды будут выполняться через sudo.
Шаг 1: Установка DHCP-сервера
1. Для установки пакета DCHP-сервера, ранее известного как dhcp3-server, нужно выполнить следующую команду:
2. После завершения установки отредактируйте файл /etc/default/isc-dhcp-server для определения интерфейсов, которые будет использовать DHCPD для обработки DHCP-запросов, при помощи опции INTERFACES.
Например, если вам нужно, чтобы демон DHCPD прослушивал eth0, задайте следующее значение:
Для этого сетевого интерфейса нужно настроить статический IP-адрес.
Шаг 2: Настройка DHCP-сервера
3. Основной файл конфигурации DHCP — /etc/dhcp/dhcpd.conf, в него нужно внести всю информацию, отправляемую клиентам.
В файле конфигурации DHCP есть два типа данных:
- параметры – указывают, как выполнять задание (например, на какое время выделять адрес), выполнять ли его вообще (например, выделять ли адреса неизвестным клиентам) или какие параметры сетевой конфигурации отправлять DHCP-клиенту.
- декларации – определяют топологию сети, описывают клиентов и предоставляемые им адреса, или применяют группу параметров к группе деклараций.
4. Для определения настроек DHCP-сервера откроем и отредактируем файл конфигурации:
Установите в начале файла следующие глобальные параметры, они будут действовать для всех указанных ниже деклараций (измените их в соответствии с вашими задачами). Это имя домена domain-name, имена DNS-серверов domain-name-servers, время аренды по умолчанию в секундах default-lease-time (если клиент не запросил его сам), максимальное время аренды в секундах max-lease-time и параметр authoritative, означающий «авторитетность» сервера в сегменте сети. Данный параметр нужен на тот случай, если клиент запросит неправильный IP-адрес — в этом случае сервер ответит ему отказом и предложит получить новый адрес.
Обратите внимание, что перед некоторыми параметрами указано слово option, а перед некоторыми — нет. Это слово задает параметры, которые передаются клиенту в сетевой конфигурации.
5. Теперь нужно указать подсеть, в нашем примере мы будем использовать DHCP в локальной сети 192.168.10.0/24.
Здесь мы использовали следующие параметры:
routers — IP-адрес маршрутизатора по умолчанию
subnet-mask — маска подсети
domain-search — имя домена
domain-name-servers — имена DNS-серверов
range — диапазон IP-адресов, выделяемый клиентам (можно указывать несколько диапазонов, но обязательно указать хотя бы один)
Шаг 3: Настройка статических IP-адресов для машин клиентов
6. Для выделения конкретным клиентам фиксированного (статического) IP-адреса нужно добавить в файл конфигурации секции следующего вида, где явно указаны MAC-адрес и статически выделяемый IP-адрес:
7. Запустим службу DHCP и установим ее автоматический запуск при загрузке:
8. Далее нужно создать правило для службы DHCP в брандмауэре (Демон DHCPD прослушивает UDP-порт 67):
Шаг 4: Настройка машин клиентов
9. Теперь можно настроить клиентские компьютеры в сети для автоматического получения IP-адресов от DHCP-сервера.
Отредактируйте файл конфигурации интерфейса Ethernet на клиентской машине (обратите внимание на имя/номер интерфейса):
Укажите следующие опции:
Сохраните и закройте файл, а затем перезапустите сетевые службы или перезагрузите систему:
Если все настроено правильно, клиентская машина должна автоматически получать IP-адреса от DHCP-сервера.
Настройка DHCP-сервера завершена. Более подробную информацию о dhcpd и dhcpd.conf с описанием всех возможных опций можно получить в соответствующих man-страницах:
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
How to Install a DHCP Server in Ubuntu and Debian
Dynamic Host Configuration Protocol (DHCP) is a network protocol that is used to enable host computers to be automatically assigned IP addresses and related network configurations from a server.
The IP address assigned by a DHCP server to DHCP client is on a “lease”, the lease time normally varies depending on how long a client computer is likely to require the connection or DHCP configuration.
How Does DHCP Work?
The following is a quick description of how DHCP actually works:
- Once a client (that is configured to use DHCP) and connected to a network boots up, it sends a DHCPDISCOVER packet to the DHCP server.
- When the DHCP server receives the DHCPDISCOVER request packet, it replies with a DHCPOFFER packet.
- Then the client gets the DHCPOFFER packet, and it sends a DHCPREQUEST packet to the server showing it is ready to receive the network configuration information provided in the DHCPOFFER packet.
- Finally, after the DHCP server receives the DHCPREQUEST packet from the client, it sends the DHCPACK packet showing that the client is now permitted to use the IP address assigned to it.
In this article, we will show you how to setup a DHCP server in Ubuntu/Debian Linux, and we will run all the commands with the sudo command to gain root user privileges.
Testing Environment Setup
We are going to use following testing environment for this setup.
Step 1: Installing DHCP Server in Ubuntu
1. Run the command below to install the DCHP server package, which was formerly known as dhcp3-server.
2. When the installation completes, edit the file /etc/default/isc-dhcp-server to define the interfaces DHCPD should use to serve DHCP requests, with the INTERFACES option.
For example, if you want the DHCPD daemon to listen on eth0 , set it like so:
And also learn how to configure a static IP address for the interface above.
Step 2: Configuring DHCP Server in Ubuntu
3. The main DHCP configuration file is /etc/dhcp/dhcpd.conf , you must add all your network information to be sent to clients here.
And, there are two types of statements defined in the DHCP configuration file, these are:
- parameters – specify how to perform a task, whether to carry out a task, or what network configuration options to send to the DHCP client.
- declarations – define the network topology, state the clients, offer addresses for the clients, or apply a group of parameters to a group of declarations.
4. Now, open and modify the main configuration file, define your DHCP server options:
Set the following global parameters at the top of the file, they will apply to all the declarations below (do specify values that apply to your scenario):
5. Now, define a subnetwork; here, we’ll setup DHCP for 192.168.10.0/24 LAN network (use parameters that apply to your scenario).
Step 3: Configure Static IP on DHCP Client Machine
6. To assign a fixed (static) IP address to a particular client computer, add the section below where you need to explicitly specify it’s MAC addresses and the IP to be statically assigned:
Save the file and close it.
7. Next, start the DHCP service for the time being, and enable it to start automatically from the next system boot, like so:
8. Next, do not forget to permit DHCP service (DHCPD daemon listens on port 67/UDP) on firewall as below:
Step 4: Configuring DHCP Client Machines
9. At this point, you can configure your clients computers on the network to automatically receive IP addresses from the DHCP server.
Login to the client computers and edit the Ethernet interface configuration file as follows (take note of the interface name/number):
And define the options below:
Save the file and exit. And restart network services like so (or reboot the system):
Alternatively, use the GUI on a desktop machine to perform the settings, set the Method to Automatic (DHCP) as shown in the screenshot below (Fedora 25 desktop).
Set DHCP Network in Fedora
At this point, if all settings are correctly configured, your client machine should be receiving IP addresses automatically from the DHCP server.
That’s it! In this tutorial, we showed you how to setup a DHCP server in Ubuntu/Debian. Share your thoughts with us via the feedback section below. If you are using Fedora based distribution, go through how to setup a DHCP server in CentOS/RHEL.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Ubuntu Documentation
Dynamic Host Configuration Protocol (DHCP)
The Dynamic Host Configuration Protocol (DHCP) is a network service that enables host computers to be automatically assigned settings from a server as opposed to manually configuring each network host. Computers configured to be DHCP clients have no control over the settings they receive from the DHCP server, and the configuration is transparent to the computer’s user.
note: this package was called dhcp3-server in versions prior to precise 12.04 LTS.
Installation
At a terminal prompt, enter the following command to install dhcpd:
You will probably need to change the default configuration by editing /etc/dhcp3/dhcpd.conf to suit your needs and particular configuration.
You also need to edit /etc/default/isc-dhcp-server to specify the interfaces dhcpd should listen to. By default it listens to eth0.
Also, you have to assign a static ip to the interface that you will use for dhcp. If you will use eth0 for providing addresses in the 192.168.1.x subnet then you should assign for instance ip 192.168.1.1 to the eth0 interface using NetworkManager. Without this step you will get an error from dhcpd when starting the service.
Configuration
The error message the installation ends with might be a little confusing, but the following steps will help you configure the service:
Most commonly, what you want to do is assign an IP address randomly. This can be done with settings as follows:
This will result in the DHCP server giving a client an IP address from the range 192.168.1.10-192.168.1.100 or 192.168.1.150-192.168.1.200. It will lease an IP address for 600 seconds if the client doesn’t ask for a specific time frame. Otherwise the maximum (allowed) lease will be 7200 seconds. The server will also «advise» the client that it should use 255.255.255.0 as its subnet mask, 192.168.1.255 as its broadcast address, 192.168.1.254 as the router/gateway and 192.168.1.1 and 192.168.1.2 as its DNS servers.
Источник
Linux DHCP Server Configuration
This tutorial covers the configuration and set-up of a Linux DHCP server. It is a prerequisite that the network interface be configured. the server also be configured.
For Linux DHCP client configuration and general Linux (Red Hat, Fedora, CentOS) network configuration, see the YoLinux Networking Tutorial
Related YoLinux Tutorials:
Dynamic Host Configuration Protocol (DHCP) automatically assigns IP addresses and other network configuration information (subnetmask, broadcast address, etc) to computers on a network. A client configured for DHCP will send out a broadcast request to the DHCP server requesting an address. The DHCP server will then issue a «lease» and assign it to that client. The time period of a valid lease can be specified on the server. DHCP reduces the amount of time required to configure clients and allows one to move a computer to various networks and be configured with the appropriate IP address, gateway and subnet mask. For ISP’s it conserves the limited number of IP addresses it may use. DHCP servers may assign a «static» IP address to specified hardware. Microsoft NetBios information is often included in the network information sent by the DHCP server.
- Lease Request: Client broadcasts request to DHCP server with a source address of 0.0.0.0 and a destination address of 255.255.255.255. The request includes the MAC address which is used to direct the reply.
- IP lease offer: DHCP server replies with an IP address, subnet mask, network gateway, name of the domain, name servers, duration of the lease and the IP address of the DHCP server.
- Lease Selection: Client recieves offer and broadcasts to al DHCP servers that will accept given offer so that other DHCP server need not make an offer.
- The DHCP server then sends an ack to the client. The client is configured to use TCP/IP.
- Lease Renewal: When half of the lease time has expired, the client will issue a new request to the DHCP server.
DHCP server installation:
- Red Hat/CentOS/Fedora: rpm -ivh dhcp-x.xxx.elx.i386.rpm
- Ubuntu/Debian 8: apt-get install dhcp3-server
( Later releases of Ubuntu (11.04) used the busybox release known as udhcpd and the configuration is NOT shown here)
Starting DHCP server:
- Red Hat/CentOS/Fedora: service dhcpd start
(or /etc/rc.d/init.d/dhcpd start for Red Hat, Fedora and CentOS Linux distributions) - Ubuntu/Debian: /etc/init.d/networking restart
Sample DHCP server config file: (DHCP v3.0.1)
- Red Hat/CentOS/Fedora: /etc/dhcpd.conf
(See /usr/share/doc/dhcp-3.X/dhcp.conf.sample)
[Potential Pitfall] : Its /etc/dhcpd.conf NOT /etc/dhcp.conf !! - Ubuntu/Debian: /etc/default/dhcp3-server
Note: The MAC addresses for the static address name server (ns2.your-domain.com), can be obtained with either of the two commands:
When dhcpd is running it will generate entries in the file: /var/lib/dhcp/dhcpd.leases
Options:
- ddns-update-style:
- interim: allows your DHCP server to update a DNS server whenever it hands out a lease. Allows your DNS server to know which IP addresses are associated with which computers in your network. Requires that your DNS server support DDNS (Dynamic DNS).
- none: to disable dynamic DNS updates or DNS is not supporting DDNS.
- ad-hoc: been deprecated and shouldn’t be used
- Default options (Red Hat/CentOS/Fedora) are set in /etc/sysconfig/dhcpd
LANs separated by routers: In order to have your DHCP broadcast pass through a router on the the next network, one must configure the router to allow DHCP relay. (Cisco: ip-helper address, Juniper: dhcp-relay) The local lan subnet configuration must come before the configuration directives of the remote LANs.
Look for errors in /var/log/messages
See dhcp-options man page below.
- Client: dhclient: DHCP client daemon (replaces dhcpcd)
- dhclient.conf: DHCP client configuration file (/etc/dhcp/dhcpd.conf)
- dhclient.leases: DHCP client lease database (/var/lib/dhcpd/dhcpd.leases)
- dhclient-script: DHCP client network configuration script
- Server: dhcpd: Dynamic Host Configuration Protocol Server daemon
- dhcpd.conf: dhcpd configuration file
- dhcpd.leases: dhcpd DHCP client lease database
- dhcp-options: dhcpd Dynamic Host Configuration Protocol options
- dhcrelay: bootp relay agent. One DHCP server to service multiple network segments.
- omshell: OMAPI Command Shell - interactive way to connect to, query, and possibly change, the ISC DHCP Server's state via OMAPI One can make the changes while the server is running.
DHCP RFC's: RFC2131, RFC1541 (obsolete), RFC2132
Источник