Время аренды dhcp сколько ставить роутер

Привет, посетитель сайта ZametkiNaPolyah.ru! Продолжаем изучать основы работы компьютерных сетей. Продолжаем рассматривать и разбирать протокол DHCP, на этот раз мы рассмотрим срок аренды IP-адреса в DHCP, который передается при помощи опции 51 (Option 51 IP Address Lease Time). В общем, нам нужно понять зачем нужно время аренды и как правильно настроить этот параметр в своей компьютерной сети.

9.4.1 Введение

Содержание статьи:

  • 9.4.1 Введение
  • 9.3.2 Зачем нужен срок аренды в DHCP и как его правильно выбрать?
    • 9.3.2.1 Зачем нужно время аренды IP-адреса в DHCP?
    • 9.3.2.2 Рекомендации по выбору и настройки времени аренды в DHCP
  • 9.3.3 Истечение срока аренды IP-адреса или как DHCP-клиент делает повторный запрос?
    • 9.3.3.1 Ключевые особенности времени аренды
    • 9.3.3.2 Option 51 IP Address Lease Time
    • 9.3.3.3 Как клиент продлевает время аренды IP-адреса
  • 9.3.4 Освобождение IP-адреса и получение нового адреса в ОС Windows
  • 9.3.5 Выводы

Сразу скажу, что в DHCP-клиенты получают IP-адреса не насовсем, а на строго определенное время, которое задается на сервере, это время называется временем аренды IP-адреса или lease time. Такой механизм в DHCP необходим, поскольку было бы глупо заставлять сервер постоянно проверять: а пользуется ли клиент выданным IP-адресом? Во-первых, у сервера может быть несколько тысяч или десятков тысяч клиентов, а его ресурсы не бесконечны, во-вторых, представьте, как не экономно расходовалась бы полоса пропускания, если бы сервер проверял доступность клиентов.

В конце концов у клиента могли бы быть написаны правила безопасности, запрещающие отвечать на всевозможные проверки, например, на ping. И что тогда, сервер бы забирал ранее выданный IP-адрес и отдавал его другому клиенту? Тогда были бы конфликты IP-адресов, что не есть хорошо. Разработчики протокола DHCP решили по-другому, придумали более гибкий и в то же время надежный подход, они решили, что клиент должен получать IP-адрес на определенное время и при необходимости продлевать это время, сервер же в свою очередь, не должен выдавать IP-адрес никому другому, пока длится время аренды, как только оно закончится и не будет продлено, сервер будет вправе освободить адрес, а затем выдать его другому клиенту.

9.3.2 Зачем нужен срок аренды в DHCP и как его правильно выбрать?

Давайте начнем с того, что поговорим: зачем в протоколе DHCP нужно время аренды IP-адреса и как его правильно выбрать. А затем посмотрим на практике, как это всё работает.

9.3.2.1 Зачем нужно время аренды IP-адреса в DHCP?

Разберемся с первой частью вопроса. Все мы прекрасно понимаем, что количество IP-адресов в мире ограничено, особенно, если речь идет о протоколе IPv4. Если же говорить про локальную сеть, то здесь IP-адресов еще меньше, это будет не совсем точно, но можно сказать, что количество IP-адресов в локальной сети ограничено количеством частных IP-адресов. Кроме того, не стоит забывать и том, что мы должны выделить DHCP-серверу пул IP-адресов, чтобы сервер начал их раздавать клиентам, этот пул тоже не бесконечен.

Думаю, приведенных выше аргументов достаточно, чтобы понять важность опции время аренды в DHCP. Эта опция нужна, чтобы клиент не владел адресом до бесконечности. Ведь может возникнуть такая ситуация в сети, при которой клиента уже в ней нет, а DHCP-сервер держит ранее выданный IP-адрес за этим клиентом и никому другому его не отдает, хотя легко мог бы это сделать, и никакого конфликта бы не произошло. Как-то не экономнененько получается с учетом дефицита IP-адресов. Заставлять DHCP-сервер опрашивать своих клиентов – затея так себе, об этом я написал выше. Значит, надо сделать так, чтобы клиент не навсегда получал адрес, а на определенное время, как я уже говорил, это время называется lease time, но не подумайте, клиент ничего серверу не платит за то, чтобы получить IP-адрес, просто надо было как-то это дело назвать.

Когда время аренды будет истекать, клиент будет вправе продлить время пользования IP-адресом, а сервер может даже ему в этом отказать в некоторых случаях. Если время аренды истекло, то клиент будет обязан прекратить использование IP-адреса, дабы чего не произошло. Также клиент вправе в любой момент времени отказать от полученного IP-адреса, для этого есть специальное DHCP-сообщение DHCPREALEASE.

Бывают такие ситуации, при которых клиент отключается от сети, проходит какое-то время, за это время срок аренды истекает, а клиент вновь подключается к сети, в таком случае он попытается запросить у сервера тот IP-адрес, который был получен ранее и если этот IP-адрес будет свободен, то сервер его выдаст, если нет, то клиент получит другой IP-адрес.

В противовес бывают обратные ситуации. Клиент отключился от сети и подключился вновь, но время аренды еще не истекло, естественно, клиент сперва попытается достучаться до сервера, чтобы выполнить продление IP-адреса, если это сделать не удается, то клиент будет использовать старый IP-адрес до тех пор, пока время аренды не истечет.

В DHCP есть одно интересное сообщение, которое нигде не реализовано, его посылает сервер клиенту и называется оно DHCPFORCERENEW, этим сообщением сервер может заставить клиента отказаться от IP-адреса до истечения срока аренды, это сообщение очень сомнительно по своему функционалу, поэтому и не реализовано.

9.3.2.2 Рекомендации по выбору и настройки времени аренды в DHCP

Тут можно сказать, что рекомендаций нет и всё зависит от того, как долго клиент находится в сети, а можно сказать, что есть одна универсальная рекомендация: настраивайте время аренды IP-адреса в соответствие с потребностями пользователей вашей сети. Все станет понятно тогда, когда мы разберем с вами несколько примеров.

Для начала представим, что под нашим управлением находится ресторан быстрого питания с суточной пропускной способностью в тысячу человек человек, среднее время, которое посетитель находится в ресторане, составляет не больше 20 минут, да и не каждый посетитель хочет подключаться к нашей сети, чтобы воспользоваться халявным Интернетом. Тогда мы легко можем прийти к выводу, что для того, чтобы все были довольны, нам хватит сети с маской /25, а время аренды IP-адреса должно быть не более 20 минут, если посетитель будет пользоваться нашей сетью дольше 20 минут, то для него ничего страшного не произойдет, его устройство просто продлит время аренды.

Следующий пример. У нас есть офисная сеть с нормальным офисным планктоном, который работает пять дней в неделю по 8 часов. В нашей сети 50 сотрудников, которые раз в год уходят в отпуск на месяц и иногда болеют, все остальное время они работают. Вообще, тут напрашивается статика, но это очень лень, когда есть DHCP-сервер, поэтому смело выставляем время аренды несколько больше, чем 30 дней и берем сеть с маской /26. Все довольны.

И третий пример с выбором времени аренды. Представим себе, что мы администрируем сеть гостинцы, которая для поддержания статуса проводит в своих помещениях выставки и конференции. Первым делом нужно для себя определить следующее: посетители в гостинице есть всегда, а вот выставки – акция разовая. Поэтому будет логично иметь на DHCP-сервере, как минимум, два пула IP-адресов, один для посетителей (хотя тут вопрос спорный, можно создать по пулу на каждый этаж гостиницы), а другой пул для разовых акций, им будут пользоваться участники конференции. Размер первого пула должен быть чуть больше, чем среднее число постояльцев, это на тот случай, если будут гости, а время аренды выставлять дольше, чем на два часа не имеет смысла, поскольку посетитель в гостинице не живет постоянно. Размер второго пула зависит от числа участников, а время аренды ставить больше, чем на час, и не стоит.

Ну а что делать, если в гостинице есть важные клиенты, которые в любом случае должны иметь доступ к сети, в этом случае для таких гостей можно зарезервировать IP-адрес и не париться. Заметили, что я все время указывал сравнительно небольшие сетки, которые должен раздавать DHCP-сервер? Почему не стоит создавать большие пулы IP-адресов, даже скажу так: почему не стоит создавать пул больше, чем /24? Дело все в том, что и клиент, и сервер обычно находятся в одной канальной среде, что будет, если клиента заштормит или случится какая другая оказия, правильно, всем остальным клиентам тоже будет плохо, и они не смогут работать, а нас это не устраивает, ведь так? У нас все должны работать. А теперь представьте – каково это – искать заглючившую железку в огромной сети.

9.3.3 Истечение срока аренды IP-адреса или как DHCP-клиент делает повторный запрос?

К сожалению, тут я ничего продемонстрировать на практике не смогу, кроме опции, в которой сервер сообщает клиенту время аренды, поэтому поверьте на слово или попробуйте самостоятельно провести эксперимент на основе моего описания.

9.3.3.1 Ключевые особенности времени аренды

Ключевые особенности протокола DHCP, связанные с временем аренды мы уже перечислили ранее, но сделали это размыто, сейчас мы просто акцентируем внимание.

  • любой клиент воспринимает IP-адрес, полученный по DHCP, как временный;
  • срок аренды задается на DHCP-сервере администратором, не ждите, что я вам скажу какой срок используется по умолчанию, то всё зависит от желания разработчиков;
  • как только срок аренды истек, клиент обязан прекратить использовать арендованный IP-адрес, ему нужно либо продлить аренду текущего, либо получить новый, но пока это происходит, старым адресом пользоваться нельзя;
  • клиент вправе продлить время аренды, о том как он это может сделать, мы поговорим ниже;
  • клиент может в любой момент прекратить пользоваться арендованным адресом, при этом он может сообщить об этом серверу при помощи специального сообщения (в этом случае сервер сразу же освободит IP-адрес), а может и не сообщать, тогда адрес будет освобожден сразу после окончания срока аренды;
  • в DHCP есть механизм, который позволяет серверу заставить клиента освободить уже занимаемый IP-адрес, для этих целей используется сообщение DHCPFORCERENEW, но я не встречал таких реализаций;
  • сервер вправе отклонить запрос клиента на продление IP-адреса, в этом случае он обязан будет послать сообщение DHCPNACK.

Эти особенности стоит помнить, при использовании протокола DHCP.

9.3.3.2 Option 51 IP Address Lease Time

Время аренды сообщает сервер клиенту, это тот процесс, за который отвечает сервер, администратор может изменить время аренды IP-адреса в любой момент. Для того, чтобы DHCP-сервер мог сообщить клиенту время аренды используется Option 51 (IP Address Lease Time). Если я всё правильно помню, то в качестве единиц измерения всегда используются секунды, ниже вы видите фрагмент дампа с сообщением DHCPOFFER, в котором сервер сообщает клиенту время, после которого IP-адрес должен быть освобожден.

9.4.1 Option 51. Сервер сообщает клиенту время аренды IP-адреса в сообщение DHCPOFFER

9.4.1 Option 51. Сервер сообщает клиенту время аренды IP-адреса в сообщение DHCPOFFER

Тут стоит заметить, что клиент начинает отсчет времени сразу после того, как получит подтверждение от сервера, а сервер начинает отсчет после того, как зарезервирует IP-адрес за клиентом. При этом клиенту нужно заботиться только о себе любимом, а серверу приходится следить и помнить время каждого клиента.

9.3.3.3 Как клиент продлевает время аренды IP-адреса

Срок аренды IP-адреса обычно обозначается буквой Т, но мы для ясности будем считать, что клиент арендовал адрес на 100 секунд, как только он получил этот адрес, пошел отсчет: 100, 99, 98, 97… Но что если клиенту мало 100 секунд, может он хочет побыть в сети немного подольше, снова проходить весь процесс получения IP-адреса, это долго и это broadcast, то есть неудобно. Поэтому клиент сделает попытку продлить IP-адрес, у него есть на это право по истечению половины периода времени аренды, это у нас время равное T/2 или 50 секунд для нашего случая.

Клиент будет пытаться продлить IP-адрес при помощи сообщения DHCPREQUEST, но в отличие от получения, продление отправляется как unicast с использованием IP-адреса того сервера, у которого клиент получил IP-адрес. Если DHCPREQUEST таки дошел до сервера, то он отправит в ответ DHCPACK тоже юникастом, так он сообщает клиенту, что запрос получил и с ним согласен, можно снова начинать отсчет, начиная со 100 секунд.

А что если выдавший IP-адрес сервер вышел из строя, но есть резервный сервер, как поступит клиент? Клиент в этом случае отправит еще одно unicast сообщение на основной сервер на 75-ой секунде (это для нашего случая, а вообще, попытка будет сделана по истечению половины оставшегося времени) при этом, если половина оставшегося времени от времени аренды, это позже, чем 7/8Т, то есть 87.5% времени аренды или 87.5 секунд для нашей ситуации, то следующая попытка продления IP-адреса будет широковещательная.

Как только истекло 87.5 секунд, клиент начнет отправлять DHCPREQUEST в сеть, используя broadcast адрес, чтобы его слышали все, в том числе и резервный DHCP-сервер, если он, конечно, есть. Если резервный сервер есть, то он может продлить аренду клиенту, в этом случае клиент получит DHCPACK, а может отказать клиенту в продлении, например, если у резервного сервера нет пула IP-адресов, в который попадает IP-адрес клиента. Тогда сервер отправит клиенту DHCPNACK, а клиент поймет, что нужно просить другой адрес.

Как только срок аренды IP-адреса истек, клиент обязан перестать его использовать и пытаться получить новый IP-адрес, либо запустить механизм APIPA и придумать сам себе случайный IP в надежде, что он будет такой не один.

9.3.4 Освобождение IP-адреса и получение нового адреса в ОС Windows

В завершении разговора поговорим о том, как происходит освобождения IP-адреса до истечения времени аренды и получение нового IP на компьютерах под управлением Windows 10. Для этого нам потребуется Wireshark, командная строка или эмулятор терминала и стандартная сетевая утилита ipconfig. Запускаем командую строку и для начала выполним команду ipconfig.

Адаптер беспроводной локальной сети Беспроводная сеть:

DNSсуффикс подключения . . . . . :

Локальный IPv6адрес канала . . . : fe80::d86b:69ce:ccc4:d47f%10

IPv4адрес. . . . . . . . . . . . : 192.168.0.100

Маска подсети . . . . . . . . . . : 255.255.255.0

Основной шлюз. . . . . . . . . : fe80::ccfc:a4ff:fee9:44d%10

192.168.0.1

Вывод команды может быть большим, как простыня, все зависит от количества сетевых интерфейсов. Выше вы видите настройки интерфейса моего ПК, который получает IP-адрес от роутера по Wi-Fi. Обратите внимание на адрес и маску подсети.

Следующим шагом нужно будет запустить Wireshark и указать интерфейс, с которого будем снимать дамп трафика. В моем случае он называется «Беспроводная сеть». С него я и получил нужную информацию. Теперь в командной строке напишем ipconfig /release и посмотрим в Wireshark.

9.4.2 Сообщение DHCPREALEASE, которое отправил клиент, чтобы освободить IP-адрес

9.4.2 Сообщение DHCPREALEASE, которое отправил клиент, чтобы освободить IP-адрес

Само сообщение ничем особо не примечательно, лишь стоит выделить два момента:

  1. Это сообщение клиент отправляет серверу адресно, а не как он это делал с другими сообщениями – при помощи broadcast.
  2. О том, что это сообщение вынуждает сервер высвободить IP-адрес говорит нам опция 53, вернее ее содержимое.

Обратите внимание на вывод команды ipconfig ниже, после того, как я освободил IP-адрес, сработал механизм, называемый APIPA, и мой компьютер назначил сам себе IP-адрес, начинающийся на 169, сделал он это в надежде на то, что в этой подсети есть и другие устройства. То есть после ручного освобождения IP-адреса, компьютер не делает повторный запрос к DHCP-серверу.

Адаптер беспроводной локальной сети Беспроводная сеть:

DNSсуффикс подключения . . . . . :

Локальный IPv6адрес канала . . . : fe80::d86b:69ce:ccc4:d47f%10

Автонастройка IPv4адреса . . . . : 169.254.212.127

Маска подсети . . . . . . . . . . : 255.255.0.0

Основной шлюз. . . . . . . . . : fe80::ccfc:a4ff:fee9:44d%10

Теперь мы хотим, чтобы клиент вновь получил IP-адрес. Нас ведь не устраивает тот, что выдал нам APIPA. Для этого напишем команду ipconfig /renew. И сразу лезем в дамп Wireshark. Тут нам уже всё знакомо.

9.4.3 При повторном получение клиент запрашивает у сервера тот IP-адрес, который у него был ранее

9.4.3 При повторном получение клиент запрашивает у сервера тот IP-адрес, который у него был ранее

Обратите внимание: никаких специальных сообщений для повторного получения IP-адреса нет, вся нужная информация находится в запросе DHCPDISCOVER, клиент с помощью 50 опции сообщает серверу о том, что он раньше брал IP-адрес 192.168.0.100 и хотел бы его взять снова, в данном случае сервер выдал клиенту этот адрес, так как он был свободен.

Вы должны были обратить внимание на то, что в дампе не было подтверждения от сервера о том, что он получил сообщение RELEASE, такого подтверждения просто нет в природе, так как оно и не нужно, даже если по каким-то причинам DHCPRELEASE не дойдет до сервера, клиент все равно освободит IP-адрес, ему на это разрешений не нужно, ведь такое действие не приведет к конфликту, и при этом ничего страшного не произойдет, если сервер не получит RELEASE от клиента, он просто освободит IP-адрес после того, как истечет срок аренды.

9.3.5 Выводы

Как видите, мы в принципе ничего  не настраивали, не экспериментировали, но зато вскрыли целый пласт особенностей работы протокола DHCP, связанных со сроком аренды IP-адреса.

The DHCP Lease Time, an important part of the DHCP settings. But what is it, how long should you set it or can you leave it on the default settings? In this article, I will explain how it works and what the recommended settings are for your network.

Every network has it, a DHCP Server. It may be built into your router or you have a server that is handling the DHCP Leases. Without it, you would have to assign every network device (computer, mobile phone, network printer) manually an IP Address.

A DHCP server does this task automatically for you ensuring that every device gets a unique IP Address to connect to the network. Now that address is leased to the client for a specific amount of time, the DHCP Lease Time.

In short, DHCP Lease Time is the amount of time in minutes or seconds a network device can use an IP Address in a network. The IP Address is reserved for that device until the reservation expires.

For computers and other network devices, to communicate on a network they need a unique IP Address. You can compare an Ip Address to the postal address of your house. There can’t be houses with the same address, otherwise, your mail might be delivered to the wrong house.

IP Addresses work the same way and in a network, a DHCP server is responsible for assigning every device a unique address. The Lease Time indicates how long a device is allowed to use that IP Address. Now, this is important because the amount of available IP Addresses is limited in a network. For a typical home network, you have a DHCP Pool of 200 Ip Addresses.

How does DHCP Lease Work?

Before we go into detail what the optimal DHCP lease time is, lets first look into how DHCP Lease works. When your computer powers up it doesn’t have an IP Address so it will need to communicate with the DHCP server for an IP Address.

If the computer doesn’t have a reservation yet for an address it will begin a new lease of the IP Address. But when it already has an active lease standing out, then it will confirm the availability of it and resume the lease.

Every DHCP lease life cycle will follow a specific pattern, it starts with the initial lease, a normal operation period, a renewal period and if the renewal fails a rebinding period.

  • At day 0 it will request a new lease
  • During normal operation, the client can use the address
  • Halfway the lease time it will try to renew the lease so it can keep the same IP address.
  • If renewing failed (DHCP server is offline for example), it will try to extend the current lease with any active DHCP Server.

DHCP Lease Time

Now let’s say you have set the lease time to 8 days (pretty long, but common in an enterprise network for wired devices). After 4 days the network device will try to renew the lease. On day 5 it is able to contact the DHCP server and renew the current lease.

At that point, the DHCP Lease life cycle will start over, so the timers (T1 and T2) will reset and the lease is valid for another 8 days.

DHCP Lease Life Cycle

Recommend DHCP Lease Time

So now we know how the DHCP lease works, how long should you set it? It depends on the situation but that are some guidelines you can use to find the optimal lease time for your network:

  • For wired devices, a lease time of 8 days is a typical period. Wired devices won’t leave the network often, so there is no reason to create a shorter period. A shorter period only increases the DHCP-related network traffic.
  • Wireless devices tend to leave the network pretty often and can stay away for a couple of days. So a smaller lease of 24 hours is pretty common. This way regular devices will keep mostly the same IP Address.
  • For guest networks and hotspots, you want a short lease time. Hotspots an hour max, while for Office guest networks 8 hours will work fine.
  • Always make sure 20% of the DHCP pool remains available. To calculate the potential amount of devices in the network and add 20%. Increase the pool size or lower the DHCP Lease Time to make it fit.

Home networks

For a home network, the default 24 hours (1440 minutes or 86400 seconds) is fine. The amount of devices in a home network is limited, maybe up to 3 per household member where your pool of IP addresses is around the 200 addresses.

But a higher lease time of 8 days would work evenly good. The reason is simple, the amount of network devices in a home network is pretty much static. The occasional guest won’t be a problem with the number of available IP Addresses.

Guest networks and hotspots

The problem with guest networks and hotspots is that you will have a lot of devices that are connected for only a short amount of time and then leaving. They might never come back, so there is no reason for a high lease time.

But don’t want to set it to low, because this will only create a lot of DHCP-Related traffic. So first you need to know how much IP Address you have available and how much visitors you expect per day or per hour.

Example case

If you have a coffee bar and you get 400 visitors a day. They stay on average 30 to 60 minutes and you have a DHCP Pool of 200 IP Address (192.168.0.10 – 192.168.0.210 for example).

When you leave the DHCP Lease Time on the default 24 hours (1440 minutes) after 200 guest no other guest can use the free wifi network. Because all the 200 IP Addresses are reserved for the first 200 guests.

So in this case you want to lower the DHCP Lease Time to one hour for example. This way the reservation is released soon enough for the other guests:

DHCP Lease Time Example

With a lease time one hour, the client will try to renew the lease after 30 minutes. At 35 min it contacts the DHCP server to extend/renew the lease. It’s granted so the timers reset, a new lease is acquired for another 60 minutes. In total, the IP Address is reserved for 95 minutes. With 200 addresses available you can have 130 guests per hour on average on your network.

Static IP Address and DHCP Pool

Permanent devices in a network can have a fixed IP Address. This is useful if you have to set Port Forwarding to a device or if you need to manage the device. Typically network devices like routers, switches, and network printers have a fixed or static IP Address.

If you leave a printer on DHCP mode, it might get a new IP Address if you turn it on after a long time of period (after a holiday for example). If this happens you might have to re-install the printer on your computer, because your computer doesn’t know anymore where to find the printer.

So always leave some room in your DHCP Pool for fixed network devices. Typically you start the DHCP Pool at 192.168.0.10 and let it end at 192.168.0.200. This leaves you with enough room for the static Ip Address. (So you can assign your printer the IP Address 192.168.0.201 for example).

Conclusion

For home networks, you don’t have to change the DHCP Lease time. Just leave it on default and you will be fine. Small Offices, Corporate Networks and Guest Networks, on the other hand, will need some planning when settings up the DHCP Server.

Also, make sure to take a look into DNS Scavenging when you are settings up DHCP and DNS servers in an enterprise network.

You may also like:

  • How to set up a home network
  • Monitoring your home network for free
  • Best router for home networks that will increase your internet speed

DHCP lease time is an important setting that can impact network performance and security. A DHCP server can be configured to give out leases for a specific amount of time, and it’s important to choose a lease time that is appropriate for your network.

In this article, we will discuss 10 DHCP lease time best practices that you can use to optimize your network.

1. Use the default lease time

The default lease time is set to 86400 seconds, or one day. This is the amount of time that a DHCP server will keep an IP address assigned to a client before it expires and is available for another client to use.

While it’s possible to change the DHCP lease time, it’s not recommended. The reason for this is that changing the DHCP lease time can cause problems with clients that are configured to use a static IP address.

If the DHCP lease time is shorter than the static IP address lease time, then the client will lose its IP address when the DHCP lease expires. If the DHCP lease time is longer than the static IP address lease time, then the client will keep its IP address even after it’s no longer using it, which can cause problems with other clients trying to use that IP address.

For these reasons, it’s best to leave the DHCP lease time at the default value.

2. Set a maximum lease time

If a DHCP server doesn’t have a maximum lease time set, then it will hand out IP addresses to clients indefinitely. This can cause problems because it means that the same IP address could be assigned to multiple devices over time, which can lead to conflicts.

It’s generally best to set a maximum lease time of around 24 hours, which should be plenty of time for most devices. If you need to support devices that require a longer lease time, then you can always create a separate scope with a longer lease time for those devices.

3. Consider setting a minimum lease time

When a DHCP client’s lease expires, it will send a DHCPRELEASE message to the DHCP server. If the client doesn’t receive a DHCPACK in response, it will assume that the DHCP server is unavailable and will start using a link-local address.

If the client does receive a DHCPACK, it will renew its lease and continue using the assigned IP address. However, if the minimum lease time has expired, the client will request a new IP address from the DHCP server.

This process can cause problems because the client will keep requesting a new IP address until it receives one. This can lead to network congestion and decreased performance.

By setting a minimum lease time, you can prevent this problem from happening. The minimum lease time is the amount of time that must elapse before the client can request a new IP address.

For example, if you set the minimum lease time to 12 hours, the client will not be able to request a new IP address for at least 12 hours. This will give the DHCP server time to process the release and renew the lease.

4. Monitor DHCP leases

If you’re not monitoring DHCP leases, you won’t be able to tell when a device has been assigned an IP address that it shouldn’t have. This could lead to all sorts of problems, such as security breaches and network outages.

Fortunately, there are a few different ways to monitor DHCP leases. One is to use a tool like SolarWinds® DHCP Scope Monitor, which allows you to see which IP addresses have been leased, for how long, and to which devices.

Another way to monitor DHCP leases is to use the native logging features of your DHCP server. This can be a bit more complicated, but it’s still possible to get the information you need.

Either way, it’s important to make sure that you’re monitoring DHCP leases so that you can spot potential problems before they cause serious damage.

5. Don’t use static IP addresses for servers

If you use static IP addresses for servers, then every time the DHCP server’s lease time expires, the server will need to be reconfigured with a new static IP address. This is not only time-consuming, but it can also lead to errors.

It’s much easier and less error-prone to simply use DHCP reservations for servers. With DHCP reservations, you can set aside a specific IP address for a server, and as long as the DHCP server’s lease time is renewed before it expires, the server will always have the same IP address.

6. Ensure that your DHCP server is secure

If an attacker were to gain access to your DHCP server, they could easily spoof DHCP responses and redirect traffic to a malicious site. This type of attack is known as a man-in-the-middle attack, and it can be devastating to your network.

To prevent this from happening, make sure that your DHCP server is properly configured and that only authorized devices have access to it. You should also consider using a firewall to further protect your DHCP server.

7. Use multiple scopes when needed

When you have a single DHCP server and multiple scopes, each scope can have its own lease time. This is important because it allows you to fine-tune the lease time for each individual scope.

For example, you may want to have a shorter lease time for your wireless network than your wired network. Or, you may want to have a longer lease time for your desktop computers than your laptops.

By using multiple scopes, you can make sure that each device on your network gets the appropriate lease time. This will help to ensure that your devices are always able to connect to the network and stay connected.

8. Limit the number of DHCP clients per subnet

If you have too many DHCP clients on a single subnet, it can lead to network performance issues. This is because each DHCP client will send out a DHCP Discover packet every time it wants to renew its lease, and if there are too many clients doing this at the same time, it can cause a flood of traffic.

To avoid this issue, make sure to limit the number of DHCP clients per subnet. You can do this by using DHCP reservations, which will assign a specific IP address to a particular DHCP client. This way, you can ensure that each client has its own IP address and won’t be competing with other clients for leases.

9. Reserve IP addresses for specific devices

When a DHCP server leases an IP address to a client, it records the MAC address of the client’s network adapter and the lease time. If the client renews the lease before it expires, the DHCP server updates the lease time.

However, if the client doesn’t renew the lease before it expires, the DHCP server assumes that the client is no longer using the IP address and can lease it to another client.

If you have a device that needs a static IP address, such as a server, you should reserve an IP address for that device. That way, even if the device is turned off or disconnected from the network, the DHCP server won’t lease the IP address to another client.

10. Avoid using DHCP on WAN links

If you use DHCP on a WAN link, and the link goes down, when it comes back up, the DHCP server will likely have given out the same IP address to another device. This will cause problems because both devices will now have the same IP address.

To avoid this problem, you should statically configure the IP addresses on devices that are connected to WAN links.

If you’ve ever set up a router at your home or business, one of the settings you may have noticed is DHCP lease time. Unless you’re an experience IT professional, it’s highly likely that you may have bypassed this setting completely, especially if you aren’t sure what it does or what value you should assign to this field.

If multiple devices are going to be connected to your internet service, it’s crucial that you understand what this term means, as well as what settings are best for your personal or business needs.

You may already be familiar with a home lease. A home lease is when a tenant signs a contract and is permitted to live in the home for the time outlined in the contract. Once that time has expired, a different tenant will most likely move into the home. Much like a lease for a house or apartment, a DHCP lease time works in the same way.

DHCP stands for Dynamic Host Control Protocol. This server is responsible for “leases” of IP addresses. Every device that is connected to a network must have an IP address, from the laptops in your home to the desktop computers in your office to smartphones, smart TVs, tablets, and other connected devices.

The IP address is similar to a home’s address. In order to receive mail, a home must have an address. In order to send and receive data, a device must have an IP address that identifies it when it is connected to the internet. Networks have two IP addresses – the first and last of a series. The numbers that fall in between are reserved for use for other devices to be used on the network.

While some devices may have a permanent IP address, others will just have temporary IP addresses, which is where the DHCP lease time – also known as client lease time – comes into play. Temporary IP addresses are assigned to other devices that don’t require a set IP – a visitor using a company’s free Wi-Fi, for example. After a set period of time, if the device is not connected to the LAN server, the IP address expires for the device and is reassigned to another device. This set period of time is the DHCP lease time.

Sound complicated? It’s not as complicated as it may seem. Take a coffee shop for example. This coffee shop advertises free Wi-Fi for its patrons. Since the average patron will not be hanging around the coffee shop all day, every day, their device (laptop, tablet, or smartphone, for example) will not require its own permanent IP address. Instead, it will be assigned an IP with a DHCP lease time.

Once the lease time expires, the IP will be assigned to another device – such as the smartphone of a new customer. This way, multiple people can connect to the network without any problems and without all of the IP addresses being taken.

When to Adjust Your DHCP Lease Time

If you run a business or work in an office where multiple devices are in use, you’ll want to consider adjusting your DHCP lease time, particularly if you have employees, customers, or clients who use their devices occasionally. Failure to adjust the lease time will likely result in a shortage of IP addresses. You want to make sure that any IP addresses that are being used just temporarily expire after a set amount of time.

You may even have to set the DHCP lease time on your home network if you have many devices. In this case, a longer lease time may be sufficient for devices that are used fairly frequently but not daily, like your router.

Finding the Optimum DHCP Lease Time for Your Needs

There is no set rule of thumb for the settings for your DHCP lease time, and it may require some experimentation based on your own personal needs (or those of your business) to get the timing just right.

Typically, the DHCP lease time default setting on most servers is 24 hours. However, this may be shorter or longer depending on your own server. Settings can be adjusted from one minute up to a certain number of days.

You’ll want to avoid setting the lease time too low as this can cause interruptions to service. For example, even in a busy doctor’s office, coffee shop, or other business that offers wireless service to its customers and clients, a person may spend much longer than one minute browsing the internet on their phones. Setting the lease time for just a few minutes will result in interruptions and aggravation. If connected device settings have a fairly quick turnaround, the settings may need to be lower than 24 hours.

In your household, if you use devices on a fairly frequent basis and don’t have many additional devices connected, the lease time can be set to several weeks or even months. The lower the number the connected devices, the higher the setting can be. The more devices that are connected, the lower the setting should be.

In an office where users go online on their computers to work, setting a static IP for each workstation is advised. However, for other device usage, keeping several IP addresses open and finding the proper lease time is necessary. Again, this should be based on turnaround times of different devices that are connected, and the number can be adjusted accordingly.

Who Sets the DHCP Lease Time?

This task is frequently performed by the system administrator. The administrator should be made aware of your particular needs to set the lease time accordingly. Of course, it is entirely possible that you may find that some adjustments are needed, or your needs may change down the road. You want to ensure that your settings are sufficient for the number of devices connected and that your server isn’t completely overloaded.

Final Thoughts

Setting the DHCP lease time for your server is critical to performance. Whether you want to keep your employees connected or you want to keep your customers happy by providing wireless, you have to make sure that this setting is adjusted to keep the server open for new connections.

When setting the lease time, it’s important to remember the following:

  • High turnaround for devices need a shorter lease time. Often, 24 hours is sufficient, but this may need to be adjusted if it’s just not working for you.
  • When fewer devices will be connected, DHCP lease times can be longer.
  • Devices that are permanently in use should have their own static IP addresses.
  • Devices that are used frequently but don’t necessarily require a static IP can have a longer lease time – think days, weeks, or even months.
  • Default times vary by server. While most are set to 24 hours, this isn’t true for every server.
  • Never set the lease time so low that it can lead to interruptions and frustration. Are you struggling to find your correct setting? Are you unsure of how to proceed? Leave your comment below to find out more about changing your DHCP lease times.

Sources

  • http://nuangel.net/2015/04/what-is-dhcp-lease-time-and-how-long-should-it-be/
  • https://www.techwalla.com/articles/what-is-dhcp-lease-time
  • http://nerderati.com/2016/07/06/why-dhcp-lease-expiration-matters-for-your-coffee-shop-router/

When you connect to a local network, either by WiFi or ethernet, a DHCP (Dynamic Host Configuration Protocol) server on your network router will issue your device with an IP address. This gives your device an ID that allows other devices to locate and connect to it. Usually, this IP address lasts for around 24 hours before it expires.

This is due to the DHCP lease time. This allows a local network to reallocate IP addresses from devices that have been disconnected for a while to other devices, freeing up IP addresses for other devices that may connect (unless you give them a static IP). 

What Is DHCP Lease Time & Should It Be Changed?

Unless otherwise specified, a typical network router will assume that any connection made to it is temporary. Your device is assigned an IP by the DHCP server with a lease time attached. If your device isn’t seen after that period expires, the lease expires, and the IP address is freed for other devices to use.

The DHCP lease time is the time given for a lease to remain active before it expires. As we’ve mentioned, 24 hours is the usual lease time issued by networks for connected devices, but this is a standard value that might not be appropriate for your network.

You can change this value, however. If you’re running an open or public network for others to connect to, you might expect a large number of short-term connections.  This is where a smaller lease time would make sense, keeping the pool of free IP addresses replenished and allowing new devices to connect.

The lease time you use depends on your own needs. You could use an hour for a restaurant WiFi network to 12 hours for a guest office network, for instance.

You’ll need administrative access to your network router to be able to change these settings. While you can view the current DHCP lease time on your PC or Mac, changing it will require access to your router.

How To View DHCP Lease Time On Windows 10

You can view the DHCP lease time for a Windows PC by using the Windows PowerShell, the replacement for the command line on Windows 10.

  • To open a PowerShell window, right-click the Windows Start menu and press Windows PowerShell (Admin). This will launch a PowerShell terminal with administrative privileges.
  • In the PowerShell window, type ipconfig /all. This will list all relevant information about your current network connections, including your DHCP lease issue and expiry times. For your network adapter, look for the Lease Obtained and Lease Expires values.

From this information, you can determine the lease time. In the example above, the lease expiry time is exactly 24 hours after the lease was first issued. This period may be shorter or longer for your connection, depending on your own network configuration.

How To View DHCP Lease Time On macOS

On a Mac, you can view DHCP lease time using the built-in Terminal app. 

  • You can launch the Terminal app by clicking Launchpad > Other > Terminal from the Dock at the bottom of your screen.
  • You’ll need to know the device name for your network device on macOS. To do this, type networksetup -listallhardwareports in the Terminal window and hit enter. This will list the name and MAC address for all network devices.
  • Once you have your device name, you can find the current DHCP lease time by typing ipconfig getpacket en0, replacing en0 with your own device name. This will list various information about your connection. The DHCP lease time will be listed next to the lease_time (uint32) option.

The DHCP lease time will be shown here as a base-16 hexadecimal value. You’ll need to convert these values to a standard decimal number. For instance, the connection above has a hexadecimal DHCP lease value of 0x15180. This converts to 86400, the length of the lease in seconds, which is equivalent to 24 hours.

Changing DHCP Lease Times On A Local Network

It isn’t possible to change the DHCP lease time in your device’s network settings as this is controlled by the DHCP server that allocates IP addresses, which is usually your network router. You’ll need to have administrative access to your router to change this.

You can usually connect to your network router by typing http://192.168.1.1 or http://192.168.0.1 in a web browser while connected to the network. You may need to check the manual for your router to determine if this is the correct way to connect, as well as determine the admin username and password to log in.

Once you’ve signed in, you’ll need to look for the appropriate Network/ LAN Settings or DHCP Settings area in your router’s settings menu. If you can’t find this, consult your user manual for further advice.

The DHCP lease value is named in various ways. For instance, on a TP-Link router, this value is called the address lease time. You can set this in minutes for this type of router, up to a maximum of 2880 (the equivalent of 48 hours). Other routers will have longer or shorter maximum lease periods.

Change the value accordingly, then save your settings. Once the DHCP lease value has been changed, the new lease time will be issued to your devices accordingly.

How To Renew a DHCP Lease

If you’ve changed your DHCP lease time, you can force any connected devices to release the existing IP lease and renew it. This will allow any changes to your DHCP lease information to be applied immediately.

  • To do this on a Windows 10 PC, open a Windows PowerShell window by right-clicking the Start menu and pressing Windows PowerShell (Admin).
  • In the open PowerShell window, type ipconfig /release. This will release the existing IP lease and disconnect.
  • Type ipconfig /renew to reestablish the connection. The network DHCP server will issue a new lease at this point.
  • On macOS, you can do this from the System Preferences menu. Press the Apple icon on the menu bar, then click System Preferences.
  • In the System Preferences menu, press Network. Select your network connection in the left-hand menu, then press Advanced.
  • In the Advanced Network menu, press the TCP/IP tab. Click the Renew DHCP Lease button to release and renew your IP lease automatically.

This will take a few seconds to complete. Once completed, your IP address will update to confirm your IP address, but you’ll need to run ipconfig getpacket en0 (replacing en0 with your own connection) from the Terminal app to check the current lease time.

Correct Network Management In Windows 10

The DHCP lease time allocated to devices on a network is an essential component in how your network works. If you’re struggling with IP address conflicts, however, you may find that it’s better to assign a static IP to devices that you use regularly.

Many of these settings need to be configured on your network router, but Windows will allow you to change network settings yourself—just be prepared for conflicts if your settings don’t match your router. This might prevent you from seeing other computers on your network, so be sure to double-check any settings you modify first.

Другие наши интересноые статьи:

  • Время аренды dhcp на роутере что это
  • Вредно ли сидеть рядом с wifi роутером
  • Все ли роутеры раздают wifi
  • Все вай фай роутеры зиксель
  • Вреден ли wifi роутер для здоровья рядом с кроватью

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии