Сброс настроек dhcp linux

How do I renew my DHCP lease?

Short of rebooting, how can I release and renew my DHCP lease? It would be useful to know a GUI and terminal method. I’d especially like to know if there is a means to do this without requiring admin privileges.

10 Answers 10

To renew your dhcp lease at the terminal:

sudo dhclient -r; sudo dhclient 

I think sudo service networking restart is a better way to go. What you suggest didn’t work for me on an 11.10 box with dhclient3. Instead, I ended up with two DHCP clients running: one dhclient3 and one dhclient . See ubuntuforums.org/showthread.php?t=1868368

sudo service network-manager restart in Ubuntu 13.10 64-bit desktop appears to properly restart network stuff and renew my DCHP lease. (From askubuntu.com/a/230751/2273 )

Useful to know for debugging: on Ubuntu 14.04 sudo service network-manager restart didn’t completely renew IP lease from DHCP. It just send a DHCP Request packet instead of a Discover . If you just want to renew your lease it’s enough, but if you are debugging DHCP you want to use the original solution.

Restarting networking isn’t a good way to go. I’m trying to do this on a remote machine. I will lose my access if I cut its networking. If it doesn’t come back, I’m screwed. No, blowing off all your network routes and taking the interface down is not a good solution to the problem «I want to renew a DHCP lease», just like getting out the shot gun is not a good solution to getting rid of a cockroach.

In my case I had to specify which card to renew:

Note: you might want to join the two on one line, as otherwise you might lose the remote connection you’re on after the first!

First release the current IP address:

then renew the IP address

.. or do them together to avoid losing connection:

sudo dhclient -r eth0 && sudo dhclient eth0 

Better: Join the commands with AND — sudo dhclient -r enp7s0 && sudo dhclient enp7s0 (replace with your eth network device)

Please edit this answer to join these together, I just got kicked off a remote box trying these separately.

for me, the change of IP was effective only after running netplan apply . Before, dhclient was showing a new IP, but it wasn’t used

In the network drop-down selector of the system tray you can press the network you are already connected to. This will make NetworkManager ask for a new lease from a DHCP server.

NetworkManager tray screenshot

This also works for wired networks, but I don’t think it works for PPP connections (mobile broadband).

If you’re on a systemd based-version of Ubuntu without a GUI (i.e. server version) then this is the way to renew the DHCP lease:

sudo systemctl restart systemd-networkd 

Note: If you’re connected via the interface whose DHCP lease you’re renewing you may get disconnected, unless you’re connected via a statically configured interface or the console.

Читайте также:  Linux название системы команда

I was testing this with dhcpdump listening on other terminal. Didn’t seem to work, only the dhclient way.

If your machine is using dhclient then you would use that. In newer versions of Ubuntu dhclient is not used and instead the DHCP client in system-networkd is used.

This works on Ubuntu 12.04 LTS:

sudo service network-manager restart 

When I do that, Network Manager asks for a new DHCP lease.

I prefer this to manually (re)starting dhclient because I’ve had problems by stale dhclient processes (ones not managed by Network Manager) spontaneously and incorrectly reconfiguring my network settings at random points when it’s least convenient.

Still relevant on Ubuntu 16.04. dhclient -r just silently does nothing with a successful exit code otherwise. 🙁

Maverick comes with nmcli , a command line interface to the network manager.

I can’t see a simple way of telling it to renew a lease, but running:

Gets you a connection list, and running:

nmcli con down id 'Connection Name' nmcli con up id 'Connection Name' 

Takes the connection down and back up. It may be possible to do something similar with the device instead.

The connection list seems to include all connections, so this will probably work with PPTP and VPN connections too.

My DHCP server still shows the lease there. (I’m trying to force a release to make a static assignment take effect)

Having just upgraded to Maverick Meerkat Beta 1, something broke in my standard, vanilla eth0 configuration which I’ve not debugged yet. The quick and dirty workaround has been

which notices that there was a (possibly dead) client already and obtains a new lease:

There is already a pid file /var/run/dhclient.pid with pid 2436 killed old client process, removed PID file Internet Systems Consortium DHCP Client V3.1.3 Listening on LPF/eth0/00:1a:92:24:9c:85 Sending on LPF/eth0/00:1a:92:24:9c:85 Sending on Socket/fallback DHCPDISCOVER on vboxnet0 to 255.255.255.255 port 67 interval 3 DHCPREQUEST of 192.168.2.2 on eth0 to 255.255.255.255 port 67 DHCPACK of 192.168.2.2 from 192.168.2.1 bound to 192.168.2.2 -- renewal in 118389830 seconds. 

This isn’t a fix, just a hack. I’ll follow-up when I figure what went bad.

Источник

How to Release old IP or force Renew DHCP lease IP in Linux

How to Release old IP or force Renew DHCP lease IP in Linux 1

In this article, we will see how to release old IP or force renew DHCP lease IP in Linux. Dynamically allocated IP is an IP leased out from a DHCP server for a particular amount of time over a network. If you are using a lease IP then you always have to renew your ip before the lease period expires. Usually, when a lease reaches 50% of its validity time period, the DHCP client unicasts a DHCP Request message to the DHCP server to request lease renewal. The same can be forced manually through a dhcp client tool in Linux Systems.

What is DHCP

The Dynamic Host Configuration Protocol is a network management protocol used on Internet Protocol networks for automatically assigning IP addresses and other communication parameters to devices connected to the network using a client–server architecture.

How to Release old IP or force Renew DHCP lease IP in Linux

How to Release old IP or force Renew DHCP Lease IP in Linux

If you have any DHCP lease IP allocated to an interface which you want to release due to certain reasons then you always have the option to release it by using DHCP client tool called dhclient. For example, in my case I have two interfaces attached to my system — enp0s3 and enp0s8 .

Читайте также:  Установить nginx linux mint

How to Release old IP or force Renew DHCP lease IP in Linux 2

To release the IP attached to both the above interfaces, we need to use sudo dhclient -r -v command. But sometimes what happens is that the IP does not get released as you can see below.

Please don’t ever try to release the IP over SSH connection as it will disconnect you from the host system and you may not be able to reconnect unless a new IP is assigned which is known to you.

How to Release old IP or force Renew DHCP lease IP in Linux 3

If we try to check again the IP got released or not using ip addr sh command then we can notice that nothing happened. The assigned IP did not got released.

How to Release old IP or force Renew DHCP lease IP in Linux 2

If you try to release IP from specific interface by choosing the interface using sudo dhclient -r -v enp0s3 command then also you can notice that the IP did not got released. This is a very common scenario faced by lot of folks hence I purposefully chosen this one while trying to explain how to release the DHCP lease IP so that you will understand what needs to be done here.

How to Release old IP or force Renew DHCP lease IP in Linux 5

Sometimes even if you try to kill the dhclient process using kill -9 command then you will notice that it is getting started every time you kill this process and the IP is not getting changed. To check the process ID of currently running dhclient program, you can use ps -ef | grep dhclient command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 6

In my case process ID(PID) is 2167 , so to kill this one we are using kill -9 2167 command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 7

Now if I try to check the process again, I can see that a new dhclient command is launched with process ID(PID) 2169 . So now you must be wondering how did this happen.

How to Release old IP or force Renew DHCP lease IP in Linux 8

Well, this happened because the network interfaces are currently controlled by Network Manager. You can verify this on Debian/Ubuntu systems by checking one of the below netplan configuration file depending on Ubuntu installation you are currently having.

Please note if you are using RHEL/CentOS based systems, then you need to check /etc/sysconfig/network-scripts/ifcfg- configuration file.

How to Release old IP or force Renew DHCP lease IP in Linux 9

You can check the running status of Network Manager by using sudo systemctl status NetworkManager command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 10

If you are also facing problems like above, then you can try below solutions that works for you.

Solution 1: Restart Network Manager

First solution you can try is that you can restart Network Manager by running sudo systemctl restart NetworkManager command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 11

Solution 2: Using nmcli command

If the first solution does not work then next you can try restarting your connection using nmcli command. Here you need to first check the current connection using nmcli con command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 12

Then first take down the connection for the interface where you need to renew the IP. In our case, let’s say we want to renew the IP of enp0s3 interface, then we need to run nmcli con down id «Wired Connection 1» command after releasing the IP as shown below.

Читайте также:  Date iso format linux

How to Release old IP or force Renew DHCP lease IP in Linux 13

Then bring up the connection using nmcli con up id «Wired connection 1» command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 14

Solution 3: Restart systemd-networkd

If second solution also did not worked out, then you can try restarting systemd-networkd once by using sudo systemctl restart systemd-networkd command as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 15

After applying above solution, you can see that you will be able to release the IP as shown below.

How to Release old IP or force Renew DHCP lease IP in Linux 16

You can verify the same by checking the status of ip assigned to network interfaces using ip addr sh command as shown below. From the output, you can see that none of the IP is assigned to both the interfaces — enp0s3 and enp0s8 . This confirms that IP release was successful.

How to Release old IP or force Renew DHCP lease IP in Linux 17

Once the IP is released, you will be able to get the new ip by running sudo dhclient -v command as shown below.

Источник

Как изменить machine-id в Linux для сброса привязки в DHCP

Заметил любопытную особенность в работе DHCP с которой раньше не был знаком. Когда клонировал виртуальные машины, заметил, что они получают одни и те же IP адреса, хотя я менял у сетевых интерфейсов MAC адреса. Я всегда был уверен, что выдача IP зависит от мака. Оказывается, что не только.

Если у вас есть желание научиться профессионально строить и поддерживать высокодоступные виртуальные и кластерные среды, рекомендую познакомиться с онлайн-курсом Администратор Linux. Виртуализация и кластеризация в OTUS. Курс не для новичков, для поступления нужно пройти вступительный тест.

В качестве DHCP сервера выступал Mikrotik. Несмотря на изменение маков, он выдавал один и тот же IP адрес разным виртуальным машинам. Я выяснил, что выдача у него привязана к Client ID. Пока не изменить его, адрес не изменится.

В Linux этот ID указан в файле /etc/machine-id. Для того, чтобы его изменить, надо его удалить и сгенерировать заново:

# rm -f /etc/machine-id # dbus-uuidgen --ensure=/etc/machine-id

Таким образом, после клонирования виртуальной машины нужно:

  1. Изменить MAC адрес сетевого интерфейса.
  2. Изменить hostname:
# hostnamectl set-hostname server-clone

Machine-id в Linux

Вроде всё. Может ещё что-то забыл? Мне не так часто приходится этим заниматься. Даже если и приходится делать клон вируталки, то обычно для тестов и запускается всё это в изолированной сети. А так, чтобы делать клон и запускать его тут же, я не практикую.

Автор Zerox

Владимир, системный администратор, автор сайта. Люблю настраивать сервера, изучать что-то новое, делиться знаниями, писать интересные и полезные статьи. Открыт к диалогу и сотрудничеству. Если вам интересно узнать обо мне побольше, то можете послушать интервью. Запись на моем канале — https://t.me/srv_admin/425 или на сайте в контактах.

3 комментария

Если DHCP-сервер на RouterOS, то можно еще использовать идентификатор клиента так: в Linux в файле /etc/dhcp/dhclient.conf параметр send dhcp-client-identifier = «какое_то_название»; или send dhcp-client-identifier = hardware;, в Windows через правку реестра. Тогда на DHCP-сервере в Leases в поле Active Client ID будет написано значение в НЕХ формате. Если (в Linux) передать параметр в кавычках — то параметр будет просто конвертирован в НЕХ формат, а если передать параметр hardware — то будет запись вида 1: (где 1 — номер сетевой карты системы).

Что-то знаки неравенства не отобразились в комментарии.
а если передать параметр hardware — то будет запись вида 1: МАС-адрес (где 1 — номер сетевой карты системы).

Источник

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