- Настройка DHCP-сервера в Linux
- Как работает DHCP?
- Шаг 1: Установка DHCP-сервера
- Шаг 2: Настройка DHCP-сервера
- Шаг 3: Настройка статических IP-адресов для машин клиентов
- Шаг 4: Настройка машин клиентов
- Linux Force DHCP Client (dhclient) to Renew IP Address
- Linux renew ip command using dhcp
- How can I renew or release an IP in Linux for eth0?
- Other options in Linux to renew dhcp
- nmcli command (NetworkManager) to renew IP address in Linux
- Linux Force dhclient to renew IP address on a CentOS 7/Ubuntu/Debian and other Linux-based server
- How do I force Linux to reacquire a new IP address from the DHCP server using desktop tool?
- Conclusion
Настройка 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 Force DHCP Client (dhclient) to Renew IP Address
I am using Ubuntu Linux. How to force Linux to reacquire a new IP address from the DHCP server? What is the command of Linux equivalent to Windows’s “ ipconfig /renew ” command?
You need to use Dynamic Host Configuration Protocol Client i.e., dhclient command. The client normally doesn’t release the current lease as it is not required by the DHCP protocol. Some cable ISPs require their clients to notify the server if they wish to release an assigned IP address. The dhclient command, provides a means for configuring one or more network interfaces using the Dynamic Host Configuration Protocol, BOOTP protocol, or if these protocols fail, by statically assigning an address. Let us see Linux command to force DHCP client release your IP address.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Linux with a terminal app |
Est. reading time | 4 minutes |
Linux renew ip command using dhcp
Warning : Releasing your IP address always brings down your network interface/WiFi. So be careful with remote systems.
The -r flag explicitly releases the current lease, and once the lease has been released, the client exits. For example, open terminal application and type the command:
$ sudo dhclient -r
Now obtain fresh IP address using DHCP on Linux:
$ sudo dhclient
How can I renew or release an IP in Linux for eth0?
To renew or release an IP address for the eth0 interface, enter:
$ sudo dhclient -r eth0
$ sudo dhclient eth0
In this example, I am renewing an IP address for my wireless interface:
- 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
Join Patreon ➔
Fig.01: Renew DHCP address example
Other options in Linux to renew dhcp
There is no need to restart network service. Above command should work with any Linux distro such as RHEL, Fedora, CentOS, Ubuntu and others. On a related note you can also try out the following commands:
# ifdown eth0
# ifup eth0
### RHEL/CentOS/Fedora specific command ###
# /etc/init.d/network restart
OR
### Debian / Ubuntu Linux specific command ###
# /etc/init.d/networking restart
nmcli command (NetworkManager) to renew IP address in Linux
The NetworkManager daemon attempts to make networking configuration and operation as painless and automatic as possible by managing the primary network connection and other network interfaces, like Ethernet, WiFi, and Mobile Broadband devices command-line tool for controlling NetworkManager. The nmcli is a command-line tool for controlling NetworkManager and getting its status. To renew IP address using nmcli for connection named ‘nixcraft_5G’ (use ‘ nmcli con ‘ command to get list of all connections):
Fig.02: nmcli command in action
Linux Force dhclient to renew IP address on a CentOS 7/Ubuntu/Debian and other Linux-based server
Most modern Linux-based system uses the systemd as a init system and here is how to force Linux to renew IP address using DHCP. Use the ip command to find out the current IP address:
ip a
ip a s eth0
Run:
dhclient -v -r eth0
OR use the systemctl command to restart network service on a CentOS 7:
systemctl restart network.service
systemctl status network.service
How do I force Linux to reacquire a new IP address from the DHCP server using desktop tool?
- Open the Activities overview (ou can also press the Super key on your keyboard) and start typing Network.
- Click on Network to open the panel.
- Choose which connection, Wi-Fi or Wired, from the left pane.
- Click on the toggle button next to the connection name to turn it off and then on again to renew IP address:
How to renew or release a dynamic IP address in Linux using GUI method
Conclusion
Linux force DHCP client to release and renew an IP address
Command | Command to release/renew a DHCP IP address in Linux | |
---|---|---|
ip a | Get ip address and interface information on Linux | |
ip a s eth0 | Find the current ip address for the eth0 interface in Linux | |
Method #1 | ||
dhclient -v -r eth0 | Force Linux to renew IP address using a DHCP for eth0 interface | |
Method #2 | ||
systemctl restart network.service | Restart networking service and obtain a new IP address via DHCP on Ubuntu/Debian Linux | |
systemctl restart networking.service | Restart networking service and obtain a new IP address via DHCP on a CentOS/RHEL/Fedora Linux | |
Method #3 | ||
nmcli con | Use NetworkManager to obtain info about Linux IP address and interfaces | |
nmcli con down id ‘enp6s0’ | Take down Linux interface enp6s0 and release IP address in Linux | |
nmcli con up id ‘enp6s0’ | Obtian a new IP address for Linux interface enp6s0 and release IP address using DHCP |
Please see the following man pages using the man command:
man 8 dhclient
man 1 nmcli
🐧 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.
Resolution provided was short but very effective.
Helped me to resolve the issue.
This worked great, I was having a bit of problems thought worked them out in the end, thought I would share.
I unplugged the network cable, then plugged back in a couple minutes later. Couldn’t access network, tried dhclient -r command and didn’t work. Found that dhcpcd was still running, so done a killall -9 dhcpcd then executed dhclient…worked!
Thanks so much! it’s work ^^
This command worked me..thanks a lot
This does not work on Ubuntu 9.04
It seems that network manager runs it own copy of dhclient.
Works for me on Ubuntu 9.04. It seems to me, that the network-manager does not notice the change. After sudo dhclient -r the command ifconfig eth0 shows no ip address at the interface. After sudo dhclient the command ifconfig eth0 shows an ip address again.
Nope. After sudo dhclient -r the interface still has the IP address. See details: http://pastebin.com/f8d2a4e2
Sure it has, depending on your dhcp server configuration. You can define how long one IP will be served to the same MAC address. Since you did not “change” your MAC address, the dhcp server might give you the same ip.
Dear sir
Please Help Me
How t o Assign IP Address For DHCP Client Linux..
Thank you for the recommendation, it works good.
I set up static DHCP assignments and then needed to switch my server over to DHCP. To do this remotely I simply put the two commands on a single line:
dhclient -r; dhclient
If you’ve set up the static DHCP to use the IP address that you’ve already given it then you shouldn’t become disconnected from your SSH session 🙂
It wasn’t working for me for me with Ubuntu 10.04…[continued if this posts]
Thank for your solution, really help me.
Well, it releases them, but when I renew it, it gives me the same ip back. I wanted a new IP. Is there way to force a NEW one?
You need to tell the dhcp server to issue a different one, typically I dhcp server will if it can issue the same address.
You may be able to tell it to forget what it last issued, or you can usually make a mapping between the mac address of your nic and the ip you want, but generally unless you do something on the server it wil reissue the same address.
Usually a DHCP server maintains a list of the leases by assigned IP and the MAC (unique identifier) of the device who has the lease.
If you don’t have access to the DHCP server in question, then the simplest way to get a new IP would be to change your device’s MAC somehow, as a DHCP server will usually give you your IP back since its still leased to you.
If you have access to the server than you can simply delete the entry, however, if its the first IP unassiged on the list, you’ll get it again unless another device takes it or if you exlude the IP address.
Hope this helps.
With some wireless routers and network modems it is possible to assign a “soft” MAC address that is different from the actual hardware MAC address. This information is usually stored in nonvolatile Flash memory, so it will survive a power-down and restart of the device. The pool of MAC addresses is finite, and there’s a slim chance if you just make one up, you could duplicate another one somewhere on the network. The best way to avoid it is rummage through your junk pile for an old network interface card (NIC) or cast-off computer with built-in NIC and “borrow” its MAC address. Blocks of MAC addresses are assigned by manufacturer and a given manufacturer normally won’t use the same MAC address twice. (However, I ran across a post within the last year by a network administrator who discovered to his horror that ALL the cheap NICs his organization had bought, made by some nameless ChiCom manufacturer, used the same identical MAC address, so confusion reigned on his organization’s intranet and nothing worked! All the NICs had to be scrapped and replaced.)
If you’re having problems getting your Linux distro to get a new IP the easiest thing to do is to just reboot your router (assuming you can do that). If that doesn’t work you can add the old address as a statically assigned DHCP address to a bogus MAC address. This will lock the Linux box out of it’s old address and force it to get the new address.
More detail, about this not working on Ubuntu:
sudo dhclient -r -pf /var/run/dhclient-eth1.pid -lf /var/lib/dhcp3/dhclient-eth1.lease eth1
This kill the running dhcp daemon which is noticed by Network Manager which then immediately downs the interface, so the dhclient can not send the DHCPRELEASE packet.
The solution is to disable NM (right clik on its icon and uncheck the first option “Enable Netwroking” – this is so on Ubuntu 10.10, other version might look a bit different), kill existing dhclient processes, then establish the connection manually, run dhclient eth0 , then run the above dhclient command to release the IP.
For connection to WPA protected WLAN networks follow the description on http://linux.icydog.net/wpa.php
(In windows this is justa matter of running “ipconfig /release wirelless*” 😛 )
Oh, webmaster please fix the typos in my previous post… 🙂
(for network device names, use the same one of course, above I used ince eth0, then eth1)
Fantastic! Worked like a charm on Ubuntu 10.10! Thanx!
Just what i needed!
Hey, is there anyway to do this command at system start?
After typing sudo dhclient -r, I lost my SSH connection…
Источник