- 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:
- Настройка DHCP-сервера в Linux
- Как работает DHCP?
- Шаг 1: Установка DHCP-сервера
- Шаг 2: Настройка DHCP-сервера
- Шаг 3: Настройка статических IP-адресов для машин клиентов
- Шаг 4: Настройка машин клиентов
- Linux find DHCP server IP address using CLI
- Linux find DHCP server IP address command line options
- The dhclient.leases file
- Find DHCP Server IP Address on Linux Command Line
- What is a DHCP Server?
- How to Find Your DHCP Server IP Address
- Find DHCP Server IP Using grep to Find Log Entries
- Using Journalctl and grep
- Find DHCP Server IP Address using Leases File
- Find DHCP Server IP Using dhclient Utility
- Conclusion
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.
Источник
Настройка 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.
Источник
Linux find DHCP server IP address using CLI
Linux find DHCP server IP address command line options
The procedure to find out your DHCP IP address in Linux is as follows:
- Open the terminal application
- Run less /var/lib/dhcp/dhclient.leases command to list your DHCP server IP address
- Another option is to type grep dhcp-server-identifier /var/lib/dhcp/dhclient.leases command to find the IP address of a DHCP server
- One can use ip r Linux command to list default route which act as the DHCP Server on most home networks
Let us see all commands and examples in details.
The dhclient.leases file
Under Linux, you need to use dhclient command to obtain and managing dhcp tasks. In order to keep track of leases across system reboots and server restarts, dhclient keeps a list of leases it has been assigned in the dhclient.leases file. On startup, after reading the dhclient.conf file, dhclient reads the dhclient.leases file to refresh its memory about what leases it has been assigned.
When a new lease is acquired, it is appended to the end of the dhclient.leases file. In order to prevent the file from becoming arbitrarily large, from time to time dhclient creates a new dhclient.leases file from its in-core lease database. The old version of the dhclient.leases file is retained under the name dhclient.leases
until the next time dhclient rewrites the database.
Источник
Find DHCP Server IP Address on Linux Command Line
I recently received an email from a reader asking “How do I find the IP address of my DHCP server”? My initial reaction was “Hmmm, good question”. That lead me to investigate the fastest way to find your DHCP server IP address from the Linux command line.
What is a DHCP Server?
A DHCP Server is a system on a network that manages dynamic configuration of client systems on the network. DHCP (Dynamic Host Configuration Protocol) is a standard network protocol used on almost all IP networks. It allows for dynamic configuration of network parameters on systems connected to the network. Before DHCP an administrator would have to configure each system individually. For more information on DHCP, see the Resource and Links section below.
How to Find Your DHCP Server IP Address
There is no simple command to show the IP address of the DHCP server on the network. However, there are places it is recorded, if you know where to look. Here are a few ways you can find the IP address of a DHCP server on your network.
NOTE: You will need root or sudo access to run all of these commands.
Find DHCP Server IP Using grep to Find Log Entries
The first method I thought of was to check the logs for the DHCPOFFER. The DHCPOFFER packet would come from the DHCP server and should be written to your logs. Here we use grep with some options (-I to ignore binary files, -R for recursive) to find the log file entry that contains our DHCP server IP address.
CentOS 7 example:
Fedora 30 example:
Ubuntu 19.04 example:
NOTE: Notice that every distribution stores it in a different log file? That is why we recursively search the whole /var/log/ directory.
Using Journalctl and grep
You can do the same as above using journalctl.
To learn more about using journalctl read “Viewing logs with journalctl“.
Find DHCP Server IP Address using Leases File
The dhclient utility stores your lease information in leases file. These lease files are kept in different places for different distros, software loads, and different versions.
NOTE: Replace [interface] with the name of your network interface (i.e. eth0, eno1, etc..)
Now use grep to find the DHCP server.
If you are using NetworkManager, you can find the lease file location by looking at the running processes (ps aux).
Now that you know where the leases file is, you can get the DHCP server IP address from that file.
We can string both of these operations together to simplify the process.
Find DHCP Server IP Using dhclient Utility
Another way would be to use the dhclient utility with some options. This also requires root or elevated privileges. The drawback of this is that the dhclient will go through the whole DHCP D.O.R.A. process. This also means that your DHCP server, network and client system need to be configured correctly. This is not much help if you are troubleshooting DHCP issues.
Conclusion
There you have it, a few different methods to find the IP address of your DHCP server. I am sure there are other ways, as with anything in Linux. If you know of another way please leave it in the comments and I will update the article.
Источник