Ошибка dhcp этот ip адрес уже используется

Обновлено 18.11.2022

DHCP error logoДобрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами производили миграцию отказоустойчивого DHCP сервера с Windows Server 2012 R2 на Windows Server 2019. В момент переноса я уже получал ряд сопутствующих ошибок, что успешно было устранено. Но они были еще не последними, так как на одной из областей DHCP я стал получать много ошибок со статусом BAD_ADDRESS: This address is already in use, что для конечных пользователей было критично, так как пропадала сеть WIFI. Давайте я попробую описать свой опыт и методы диагностики с устранениями.

Описание ошибки BAD_ADDRESS: This address is already in use

На новой паре DHCP-серверов я стал на области WIFI получать много ошибок:

BAD_ADDRESS: This address is already in use

Ошибка получения IP адреса на DHCP. BAD_ADDRESS This address is already in use

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

DHCP Server replicate scope

Далее, что я стал делать, это смотреть логи DHCP сервера, для этого в просмотре событий есть соответствующие журналы:

  • Microsoft-Windows-DHCP Server Events/Admin
  • Microsoft-Windows-DHCP Server Events/Operational
  • Microsoft-Windows-DHCP Client Events/Admin

Первое чем были забиты логи, это предупреждение с ID 1063:

There are no IP addresses available for lease in the scope or superscope «WIFI_Pyatilistnik».

There are no IP addresses available for lease in the scope or superscope

Предупреждение ID 1342:

IP address range of scope WIFI is out of IP addresses.

IP address range of scope WIFI is out of IP addresses.

Я увидел, что Ip-адреса из определенного скоупа просто закончились. Остальные клиенты, которые пытались получить от DHCP-сервера IP-адрес, просто дропались, это видно в событии ID 20287.

DHCP client request from F09E40097EC1 was dropped since the applicable IP address ranges in scope

DHCP client request from MAC was dropped since the applicable IP address ranges in scope

Это так же спровоцировало шквал ошибок ID 20292.

ID 20292: A BINDING-ACK message with transaction id: 28044 was received for IP address: 10.xx.xx.82 with reject reason: (Outdated binding information ) from partner server: dhcp04.pyatilistnik.org for failover relationship: dhcp03.pyatilistnik.org-dhcp04.pyatilistnik.org.

A BINDING-ACK message with transaction id

Зайдя в свойства области я лицезрел картину, как свыше 2000 IP-адресов были зарезервированы, и люди просили еще😄

Закончились IP-адреса на области DHCP

Как устранить ошибку BAD_ADDRESS

В данной ситуации у меня наложились два момента:

  • 1️⃣Количество пользователей увеличилось с 1200 до 1600 + их мобильные устройства
  • 2️⃣В момент загрузки информации, об областях и аренде в них, были скопированы записи аренды со статусом Expired, но об этом чуть ниже.

Ранее в другой статье я вам рассказывал интересный момент работы DHCP-сервера Microsoft, там после окончания аренды, если клиент не стал продлевать, данный IP забирает DHCP-сервер, но он его по умолчанию не отдает еще целых 4-часа, это называется льготный период (grace period). Его нужно уменьшать. В моем случае, когда все IP-адреса заняты и куча со статусом BAD_ADDRESS, нужно искать Expired адреса и чистить их. Для этого у вас должен быть ScopeId и мои команды😄. Чтобы посмотреть все IP-адреса со статусом Expired находящихся в льготном периоде, выполните в PowerShell в режиме администратора на первом DHCP-сервере команду:

Get-DhcpServerv4Lease -ScopeId 10.168.31.0 -AllLeases | where-object {$_.AddressState -like «Expired»}

Вывод всех IP адресов со статусом Expired

На дворе было 15 ноября 2022, а записи были аж от 28 октября 2022, это оставшийся мусор после миграции DHCP, который по какой-то причине не почистился сервером из области льготного периода.

Вывод всех IP адресов со статусом Expired-2

Я решил посчитать, сколько у меня так застряло IP адресов, для этого можно использовать вот такой код:

$obj = Get-DhcpServerv4Lease -ScopeId 10.168.31.0 -AllLeases | ? {$_.AddressState -like «Expired»}

($obj | Measure-Object).Count

Таких застрявших оказалось свыше 540 штук, что было 25% от общего пуля.

Количество IP-адресов со статусом Expired

Естественно я попытался их почистить, для этого есть PowerShell код:

$computername = «Тут пишите адрес вашего DHCP»

$scopeid = «Тут пишите имя вашей области»

foreach ($object in Get-DhcpServerv4Lease -ComputerName $computername -ScopeId $scopeid)

{

if ($object.leaseExpiryTime -le (Get-Date))

{

$object.hostname

Remove-DhcpServerv4Lease -ComputerName $computername -IPAddress ($object.IPAddress).IPAddressToString

}

}

или

$computername = «Тут пишите адрес вашего DHCP»

$scopeid = «Тут пишите имя вашей области»

foreach ($object in (Get-DhcpServerv4Lease -AllLeases -ComputerName $computername -ScopeId $scopeid))
{

if ($object.leaseExpiryTime -le (Get-Date))
{
$object.hostname

Remove-DhcpServerv4Lease -ComputerName $computername -IPAddress ($object.IPAddress).IPAddressToString # -WhatIf
}
else
{
# $object.leaseExpiryTime
}
}

Массовое удаление IP-адресов со статусом DHCP

Но у меня повалилась куча ошибок:

Remove-DhcpServerv4Lease : Failed to delete lease 10.xx.xx.142 on DHCP server dhcp03.pyatilistnik.org.
At line:12 char:9
+ Remove-DhcpServerv4Lease -ComputerName $computername -IPAddre …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (10.xx.xx.142:root/Microsoft/…cpServerv4Lease) [Remove-DhcpServerv4Lease], CimException
+ FullyQualifiedErrorId : WIN32 232,Remove-DhcpServerv4Lease

В итоге в области namespaces нет данных Ip-адресов, через netsh так же не удалялось.

Ошибка удаления IP-адресов со статусом Expired

Если на первом сервере выбрать в команде второй DCHP, то ошибка сохранится, а вот если зайти на второй DHCP по RDP ну или удаленно подключиться через PowerShell, то вот там как раз все прекрасно удалится, дошел я до этого не сразу.

Еще оговорюсь, что я мог пересоздать scope, но мне не хотелось делать лишних телодвижений и менять настройки, тем более со скоупом в 2000 клиентов

Успешное удаление Ip-адресов со статусом Expired

В результате 500 IP-адресов снова появились в доступном обращении.

Уменьшение времени льготного периода и очистки базы данных DHCP

В больших сетях, где большое количество клиентов я советую  grace period на небольшой промежуток, то используют два ключа реестра.

  • Интервал очистки базы данных можно сократить, обновив раздел реестра DatabaseCleanupInterval тип DWORD в разделе HKLM/System/CurrentControlSet /Services / DHCPServer/Parameters. Хочу отметить, что по умолчанию значение у ключа DatabaseCleanupInterval  составляет 60 минут, когда он будит проходить и вычищать Expired записи после того, как заканчивается «Льготный период (grace period)«. По умолчанию он создан уже на DHCP сервере, я советую выставить его минут 30. Так же его можно задать и через PowerShell

Set-DhcpServerDatabase -ComputerName «dhcpserver.pyatilistnik.org» -FileName «D:NewDhcpPathdhcp.mdb» -BackupPath «D:NewDhcpPathbackup» -CleanupInterval 30

Смена периода очистки адресов в DHCP через DatabaseCleanupInterval

  • Вы можете сократить льготный период аренды, создав или обновив раздел реестра LeaseExtension тип DWORD в разделе HKLM/System/CurrentControlSet /Services/DHCPServer/Parameters. Значение может быть указано в десятичном формате и должно быть в минутах. Я обычно ставлю 60 секунд.

Создание ключа реестра LeaseExtension

После этого вам необходимо произвести перезапуск службы DHCP, либо через графическую оснастку services.msc, которую можно запустить через «окно Выполнить» или же введите команду в PowerShell.

Restart-Service DHCPServer

Согласование БД DHCP

Еще на уровне scope или всего сервера DHCP, есть такая функция согласования (reconcline), используйте ее когда у вас есть какие-то проблемы на DHCP с БД.

согласования (reconcline) на DHCP сервере

Вы должны добиться того, что у вас БД ответила «The database is consistent«

успешно выполнено согласования (reconcline)

Дополнительные ссылки

  • https://learn.microsoft.com/en-us/powershell/module/dhcpserver/set-dhcpserverdatabase
  • https://windata.ru/windows-world/lokalnaya-set/vosstanovlenie-bd-dhcp-soglasovanie-oblastej/

Надеюсь, что вам удалось решить свою проблему с моим скромным опытом. С вами был Иван Сёмин, автор и создатель IT портала Pyatilistnik.org.

  • Remove From My Forums
  • Question

  • Hello, I have a 80/20 split scope for some Cisco Wireless Access Points.  The scope serves 203 addresses 163 from one server and 41 from the other server.  We have been installing these Access Point just fine until the last week when we reached
    96 Access Points and that is when I noticed we are seeing bad_address This address is already in use in the Address Leases folder on both servers in the Address Leases folder for the scope the scope In Use statistics is 100%.  I have
    tried just deleting the bad_addresses out of the Address Leases folder but they just show up again after a few minutes.  If I ping one of the bad addresses it times out so I have a couple of questions:

    How do I go about cleaning up the bad addresses and resolve the situation?

    How do I expand the IP range of a scope that is split?  Do I have to delete one scope and then modify the source scope then re-add the second scope or is there a better way?

    Environment

    2 Windows 2008 R2 Enterprise Servers

    3 Cisco Wireless Controllers

    Need to install 200 Cisco 1142n APs

    Thanks in advance for any advice:)

Answers

  • Hello Issatia,

    First, the 80/20 design is really antiquated and meant for scenario like a main/remote office connected with a slow link.  The remote office would have 80% and the main would have 20%.  We can go into more details about this, but for scenarios
    where you just want to build a redundant DHCP infrastructure where the WAN connections are not of concern, a 50/50 design is more appropriate and much easier to manage.

    I do not recommend a clustered solution for DHCP as clustering services adds an extra layer of complexity and cost (shard storage for the DB), and a 50/50 works just as well, and more cost effective.

    You create the same scopes on both servers, and just add the appropriate exclusions to ensure there is no overlap of available IPs.

    With regard to BAD ADDRESS leases, they remain in effect for 1 hour, auto removed, but of course will return when the DHCP server tries to assign a lease for an IP that is in use on the network.

    This could be caused by several reasons…

    1) you have overlap in your DHCP scopes

    2) there are clients on the network that are assign static IPs within the DHCP range

    3) you have another unknown DHCP server assigning addresses in the same range.

    You first need to determine the cause before you can fix the issue with the correct solution.


    • Marked as answer by

      Thursday, June 21, 2012 1:20 AM

  • Ugh, I wouldnt put that many addresses into one subnet, I know we have faster equipment these days and faster links, but broadcast storms could be a killer.  I know this is off topic for the DHCP question, but why are you not using Layer 3 for your
    access points?  The only downside to L3 on the WLC is that you have to prime every AP before it is deployed, but as long as the AP has connectivity back to the WLC it was primed to, it can use a local scope.

    Are your wireless clients connecting to the same VLAN (91)? You could have someone or multiple someones snagging addresses or putting statics on their devices over the wireless causing your bad address issue.  You can require DHCP on the SSID to help
    mitigate this.

    • Marked as answer by
      Aiden_Cao
      Thursday, June 21, 2012 1:20 AM

  • Thanks for all the help I ended up calling Cisco TAC and it ended up being the models of WLC we were using had a 48 AP limit per ap-manager port.  Once I added either a physical port or LAG setup then all the MS DHCP errors went away.

    • Marked as answer by
      Aiden_Cao
      Friday, June 22, 2012 1:48 AM

We have recently migrated server from windows server 2008 to 2012 and it has two roles; DHCP and DNS.

All of a sudden we started mailers from Network team stating huge ARP requests are created from DHCP servers.

When checked in DHCP console, we find many ip getting bad address with strange 8 digit unique id rather than the traditional MAC id.

Client IP Address
Name
Lease Expiration
Type
Unique ID
Description
Network Access Protection
Probation Expiration
Filter Profile
Policy

10.255.124.34 BAD_ADDRESS
5/23/2018 5:09:58 PM
DHCP 227cff0a
This address is already in use
Full Access N/A
None
10.255.124.36 BAD_ADDRESS
5/24/2018 3:40:17 AM
DHCP 247cff0a
This address is already in use
Full Access N/A
None
10.255.124.56 BAD_ADDRESS
5/23/2018 4:43:02 PM
DHCP 387cff0a
This address is already in use
Full Access N/A
None

On further analysis we could able to figure out that these are the reverse hex value of the IP addreess.

Example ;

10 — oa

255 — ff

124 — 7c

56 — 38

We couldn’t figure out why we are getting these Unique ID and bad address, Since we are not able to track from firewall / DHCP and systems logs.

Not sure what device went rogue in our environment either the the NS device or DHCP or Windows clients.

Any help would be highly appreciated, Thanks.


Satheesh


0

3

Доброго времени суток, уважаемые.
есть проблемка над которой долбусь уже около недели, может вы что нить умное подскажете и так поехали:

есть сеть в которой ПРОВАЙДЕРСКИЙ dhcp раздает внешние ip адреса (БЕЗ КАКИХ БЫ ТО НИБЫЛО ПРИВЯЗОК т.е. ), есть комп на котором довольно долго уже ip прописан статикой, теперь появилась необходимость на этот комп поставить линукс вкатал fedora (RFRemix 16), почему именно ее, а не что нить другое это отдельная тема и к данной не имеет особого отношения.поставил начал настраивать и наткнулся на пролему: ip я прописал статически как и на второй системе (к слову там вин7), спустя некоторое время сеть отвалилась. выяснил что падения сети связаны с тем что dhcp не видит прописаного статикой ip и выдает его другой машине (выдало соседней машине потому и увидел), при этом если загрузить вин 7 то все норм, как я уже говорил там так же забита статика. ip не выдается другим компам и все отлично работает.

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

What is Bad Address?

We know that all the computers, servers, mobile devices communicate through the internet via IP address each, and every device has its separate unique IP address. Devices will get the IP address from the DHCP server when it connected to the network. There are two types of IP address allocation, static and Dynamic (DHCP). In some cultivation, devices share the same IP address from the DHCP server, this cause IP address conflict and will get the popup stating an IP address conflict detected. BAD address is if the same address assigned to 2 machines it will conflict and make it as a BAD address in DHCP terms.

How the Bad_address Entry is happening on the DHCP server?

For example, in any multi-project Organization, which handle different project as per the client requirement may have different Project VLAN. Each project may contain 50 users, so while creating a DHCP scope for that project 50 IP range will be created, first and last IPs are automatically omitted by the DHCP server remaining IP address are automatically allocated to the system by the DHCP server. Each IP has a maximum IP release duration Time. For imaging purposes, most of the organization enables Ghost IP after imaging IT will enable Project VLAN. Ghost VLAN IP release duration time maybe 6-8 hours after 8 hours the IP will be automatically released, during this duration, any system picks the IP and not completed 8 hours duration time before that anyone clears the scoop for another set of Reimage. Now the IP will stay in the system and again while the DHCP server tries to allocate the IP within the range the same IP will allocate to some other system this will cause IP address conflict.

How DHCP server Detects the Conflicts?

The DHCP server detects conflicts by pinging an IP address before offering that address to clients. If the ping is successful (a response is received from a computer), a conflict is registered and that address is not offered to clients requesting a lease from the server. The DHCP server pings only address that have not been successfully and previously leased. If a client receives a lease on an IP address that it already had or is requesting a renewal, the DHCP server does not send a ping. If conflict detection is enabled, an administrator-defined number of pings are sent. The server waits 1 second for a reply. Because the time required for a client to obtain a lease is equal to the number of pings selected, choose this value carefully as it directly impacts the overall performance of the server. In general, one ping should be sufficient. A DHCP server receiving a reply to any of the pings (meaning there is a conflict) attaches a BAD_ADDRESS value to that IP address in the scope and will try to lease the next available address. If the duplicate address is removed from the network, the BAD_ADDRESS value attached to the IP address can be deleted from the scope’s list of active leases, and the address returned to the pool. Addresses are marked as BAD_ADDRESS for the length of the lease for which the scope is configured. If your network includes legacy DHCP clients, enable conflict detection on the DHCP server. By default, the DHCP service does not perform any conflict detection. In general, conflict detection should be used only as a troubleshooting aid when you suspect there are duplicate IP addresses in use on your network. The reason for this is that, for each additional conflict detection attempt that the DHCP service performs, additional seconds are added to the time needed to negotiate leases for DHCP clients.

Possible Solutions:

Checking the Old DHCP logs and clearing It. This is caused mostly by a malfunctioning DNS. Delete the BAD IP addresses from your DNS entries, then restart DNS. Delete it on DHCP as well. If the entire IP scoop becomes bad, then completely refresh the scoop this will release all the IP from the range and renew with New IPs.

Понравилась статья? Поделить с друзьями:
  • Ошибка dhcp сервера что это
  • Ошибка dhcp сервера xiaomi на роутере
  • Ошибка dhcp не включен на сетевом адаптере как включить
  • Ошибка dhcp не включен на сетевом адаптере ethernet
  • Ошибка dhcp на принтере xerox b205 как исправить