Linux переполучить ip адрес от dhcp сервера

How do I force Linux to reacquire a new IP address from the DHCP server?

Where interface is the device you want to get a new address for.

The -r flag forces dhclient to first release any leases you have, you can then use this command to request a new lease:

 -r Tell dhclient to release the current lease it has from the server. This is not required by the DHCP protocol, but some ISPs require their clients to notify the server if they wish to release an assigned IP address. 

After this command my Debian failed to get a new IP, but after a reboot I was assigned to a new one, so it work’s!

@EricNord — You can still do this via SSH. Use the ‘at’ command to schedule a one-time command, 1 minute in the future or less, disconnect your SSH session then reconnect. You could even automate it, and reconnect to the same host via Multicast DNS (assuming you have that running, most home networks do)

Either of the following should get it to renew.

/etc/init.d/networking restart 

I wouldn’t recommend running either over an SSH connection, although you’ll probably get away with the first one if it doesn’t come back with a new ip address.

SSH connections will tolerate a few seconds of «disconnect» provided that you get the connection back up in a few seconds at the same IP address. Under these conditions, I have never lost a connection during /etc/init.d/networking restart , even when it was taking more than 5 seconds to come back up.

Worst case you reconnect. If you’re trying to automate this, see mDNS and ‘at’ command, and use a wrapper script to orchestrate the change and the reconnect.

Would comment p.campbell, but I have only 1 reputation and therefore cannot, first I review installed interfaces:

release IP from selected interface (e.g. eth0, eth1, enp1s0, sit0, wlan0. ):

sudo dhclient -r *interface* 

request new IP from DHCP server (alert on error):

sudo dhclient -1 *interface* 

Ubuntu 16.04 LTS confirmed

If you’re using the dhcpcd tool then:

dhcpcd -k interface dhcpcd -n interface 

The first says to release and deconfigure the interface, and the second says to reload configuration and rebind the interface again.

If the MAC address of the interface isn’t changed, the DHCP server may assign it the same address when renewing. Therefore, a simple release and renew with dhclient may not acquire a new address. Change the MAC address and acquire a new IP address with the following commands. Don’t forget to write the original down if you need to revert back to it at a later time.

ifconfig down ifconfig hw ether ifconfig up 

This was so helpful, thank you! No number of dhclient -r or ifconfig down gave me a new IP address on my work network, until I changed the MAC address to something random using that command.

Читайте также:  Мессенджер локальной сети linux

In systems where NetworkManager is on, 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

Источник

How to Renew DHCP IP Address in Ubuntu

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

There are several occasions when we need to renew the DHCP-assigned system IP address, for example:

  • For resolving connection issues
  • For resolving IP address conflict in a place where many computers use the same DHCP server
  • For some reason, the administrator sets a short lease time for the assigned DHCP IP

Besides these reasons, when a computer switches to a different network, its IP also changes.

In this tutorial, we’ll discuss renewing the DHCP-assigned IP address on a Ubuntu 22.04 system. Let’s first see an overview of the DHCP protocol.

2. Dynamic Host Configuration Protocol (DHCP)

To identify a computer/host on a network, we use IP addresses. Using these IP addresses, computers communicate with each other on a network. Basically, there are two ways of configuring IP addresses on a client machine:

  1. Static IP Allocation: Manually setting IP configuration on each individual client
  2. Dynamic Allocation: Automatically assigning IP addresses through a DHCP server

A DHCP server automatically assigns IP addresses to connected hosts on a network. The client cannot interfere with the DHCP settings they receive. However, these settings are transparent to the client side. An IP address set using the above way is not a permanent one, and we refer to it as a DHCP lease. If we do not renew it, the DHCP lease may be allotted to another computer. Therefore, to renew the lease, the client has to periodically check back with the DHCP server.

3. DHCP Clients

Broadly speaking, there are three DHCP clients that are common on Ubuntu:

However, not all versions of Ubuntu support all three clients. This is true for other Linux-based distributions too. For example, some of them come shipped with only one of the three clients, whereas others may come shipped with two or all of the three. However, dhclient is a commonly available DHCP client on Ubuntu systems.

Ideally, every system has a default DHCP client. On Ubuntu 22.04, the dhclient is the default DHCP client. At the time of writing this article, the other clients pump and dhcpcd are not available on Ubuntu 22.04.

Since we are working on Ubuntu 22.04 system, we’ll have to use dhclient as the DHCP client.

Читайте также:  Linux number open files

4. Process of DHCP Client-Server Interaction

There are several messages that pass between the DHCP server and the client, as described below:

  1. DHCPDISCOVER: the client broadcasts a DHCPDISCOVER message asking for an IP address
  2. DHCPOFFER: in response to the DHCPDISCOVER message, a DHCP server may transmit a DHCPOFFER message
  3. DHCPREQUEST: the client will respond with a DHCPREQUEST message for a DHCPOFFER message from the DHCP server it wants to be configured with. The client broadcasts this message so all DHCP servers on the network can be informed about the selected server
  4. DHCPACK: When a client finalizes a DHCP server, it receives a DHCPACK message from this DHCP server. This message also has other required configuration details
  5. DHCPRELEASE: The client can send a DHCPRELEASE message to terminate the lease

After the last DHCPACK message, the client can use the leased IP address and other settings till the end of the lease time.

When half the lease time is over, the client can request IP renewal. For this, the client sends a DHCPREQUEST message to the DHCP server. If the current DHCP server says yes to the request, it responds with a DHCPACK message.

However, if the client does not get a response, the client might go on with the current DHCP settings. It can continue using them until the lease time is over.

Once the lease time is over, it is mandatory for the client to again restart with the DHCPDISCOVER procedure.

5. Renewing DHCP IP Using dhclient

Let’s first check if the dhclient service is running on our Ubuntu 22.04 system:

$ ps fax | grep dhclient 4988 pts/0 S+ 0:00 | \_ grep --color=auto dhclient

The ps command shows the information corresponding to different services running on the system.

Let’s now check our current leased DHCP IP address on our target interface wlo1:

$ ip addr | grep wlo1 wlo1: mtu 1500 qdisc noqueue state UP group default qlen 1000 inet 192.168.35.150/24 brd 192.168.35.255 scope global dynamic noprefixroute wlo1

As we can see, the current assigned IP is 192.168.35.150. Let’s release our leased DHCP IP using the -r flag of the dhclient command:

The -r flag releases the current DHCP lease and halts the running DHCP client. Note that releasing an IP address can result in loss of connection, so carefully perform this step on remote systems. Next, we will now request a new DHCP IP from the server:

$ sudo dhclient -v Internet Systems Consortium DHCP Client 4.4.1 Copyright 2004-2018 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/wlo1/d0:c5:d3:3d:22:cf Sending on LPF/wlo1/d0:c5:d3:3d:22:cf Listening on LPF/eno1/c8:d9:d2:ee:4f:f9 Sending on LPF/eno1/c8:d9:d2:ee:4f:f9 Sending on Socket/fallback DHCPDISCOVER on wlo1 to 255.255.255.255 port 67 interval 3 (xid=0xaee34c7f) DHCPDISCOVER on eno1 to 255.255.255.255 port 67 interval 3 (xid=0xebcb010d) DHCPOFFER of 192.168.35.151 from 192.168.35.47 DHCPREQUEST for 192.168.35.151 on wlo1 to 255.255.255.255 port 67 (xid=0x7f4ce3ae) DHCPACK of 192.168.35.151 from 192.168.35.47 (xid=0xaee34c7f) bound to 192.168.35.151 -- renewal in 1452 seconds.

Let’s again check back our IP on the wlo1 interface:

$ ip addr | grep wlo1 wlo1: mtu 1500 qdisc noqueue state UP group default qlen 1000 inet 192.168.35.151/24 brd 192.168.35.255 scope global dynamic wlo1

As we can see, the IP address has now changed to 192.168.35.151.

Читайте также:  Linux oracle database service

The syslog file stores the logs generated by the DHCP server. We can search through these logs for DHCP logs:

$ cat /var/log/syslog | grep dhcp Oct 30 05:10:01 LHB NetworkManager[840]: [1667086801.8104] dhcp4 (wlo1): activation: beginning transaction (timeout in 45 seconds) Oct 30 05:10:01 LHB NetworkManager[840]: [1667086801.8418] dhcp4 (wlo1): state changed new lease, address=192.168.35.150 Oct 30 05:40:01 LHB NetworkManager[840]: [1667088601.7480] dhcp4 (wlo1): state changed new lease, address=192.168.35.150 

These logs are very helpful while troubleshooting DHCP issues.

6. Conclusion

In this article, we have learned how we can acquire a new IP address on the Ubuntu system. Specifically, we have used the dhclient utility to renew our IP configuration.

Источник

Как заставить Linux повторно получить новый IP-адрес с сервера DHCP?

Средой является Debian , хотя ответ будет распространяться на все дистрибутивы.

Вы также можете использовать эту команду:

Где interface находится устройство, для которого вы хотите получить новый адрес.

В -r флаге сила dhclient в первый выпуск любой аренды у вас есть, вы можете использовать эту команду , чтобы запросить новый:

 -r Tell dhclient to release the current lease it has from the server. This is not required by the DHCP protocol, but some ISPs require their clients to notify the server if they wish to release an assigned IP address. 

После этой команды моему Debian не удалось получить новый IP, но после перезагрузки мне был назначен новый, так что он работает!

Любое из следующего должно заставить это возобновить.

/etc/init.d/networking restart 

Я бы не рекомендовал работать по SSH-соединению, хотя вам, вероятно, не удастся использовать первое, если оно не вернется с новым IP-адресом.

Соединения SSH будут терпеть несколько секунд «разъединения», если вы восстановите соединение через несколько секунд с того же IP-адреса. В этих условиях я никогда не терял соединение /etc/init.d/networking restart , даже когда на восстановление ушло более 5 секунд .

Я бы прокомментировал p.campbell, но у меня только 1 репутация, и поэтому я не могу, сначала я проверяю установленные интерфейсы:

освободить IP с выбранного интерфейса (например, eth0, eth1, enp1s0, sit0, wlan0, . ):

sudo dhclient -r *interface* 

запросить новый IP с сервера DHCP (предупреждение об ошибке):

sudo dhclient -1 *interface* 

Ubuntu 16.04 LTS подтвердил

Если вы используете dhcpcd инструмент, то:

dhcpcd -k interface dhcpcd interface 

Первый говорит, чтобы остановить демона, а второй говорит, чтобы запустить его снова.

Если MAC-адрес интерфейса не изменился, DHCP-сервер может назначить ему тот же адрес при обновлении. Поэтому простой выпуск и обновление с помощью dhclient может не получить новый адрес. Измените MAC-адрес и получите новый IP-адрес с помощью следующих команд. Не забудьте записать оригинал, если вам нужно вернуться к нему позже.

ifconfig down ifconfig hw ether ifconfig up 

Это было так полезно, спасибо! Ни один номер dhclient -r или не ifconfig down дал мне новый IP-адрес в моей рабочей сети, пока я не изменил MAC-адрес на случайный, используя эту команду.

Источник

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