Overview
A DHCP scope is an administrative grouping of IP addresses for a network subnet. With scopes you can configure common network settings for all clients receiving addresses, such as DNS servers and network gateways.
Scopes can filter hosts by name, MAC address, and operating system to either allow them or disallow them from receiving an IP address. Scope policies can be configured to assign different options to hosts based on their name, MAC address, or operating system. For example, we can create a policy that configures the NIS server for a Linux host in addition to options set at the scope level.
This tutorial will guide you through configuring DHCP scopes on Windows Server 2012 R2.
Create a New Scope
- Launch the DHCP console.
- From the tree on the left side of the console, expand the DHCP server’s hostname node.
- Select and then right-click IPv4.
- From the IPv4 context menu, select New Scope.
FIG1 – Windows DHCP New Scope context menu - When the New Scope Wizard dialog box appears, click Next.
- On the Scope Name screen, enter the name of your new scope. You should give it a description to document its purpose. When done, click Next.
FIG2 – DHCP New Scope Wizard: Scope Name - On the IP Address Range screen, enter a starting IP address followed by an Ending IP address. This create the scope’s range, which will be used to assign addresses to clients.
- Under Configurating settings that propagate to DHCP client section of the IP Address Range screen, either enter a subnet bit length (CIDR) in the Length field, or enter the dotted decimal notation of the subnet mask.
FIG3 – Windows DHCP New Scope Wizard: IP Address Range - Click Next.
- On the Add Exclusions and Delay screen, we can set IP addresses from within the range we defined that should be excluded. For example, if our range includes the IP address of our network gateway, we probably do not want our clients to use it, so we would add its IP address to the exclusion list. Click Next when done.
FIG4 – Windows DHCP New Scope Wizard: Add Exclusions and Delay - On the Lease Duration screen, enter the length of time a client should be assigned an IP address. When done, click Next.
- On the Configure DHCP Options screen, select Yes, I want to configure these options now, and then Click Next.
- On the Router (Default Gateway) screen, enter the IP address of the gateway clients should use. Click Next when done.
- On the Domain Name and DNS Servers screen, enter the IP addresses of all DNS servers the client should use. Click Next when done.
- On the WINS Servers screen, if you have WINS servers add them here. Click Next when done.
Most Windows environments no longer use WINS for name resolution. Although, some legacy applications and hardware may still require it, so check your environment before skipping this.
- On the Activate Scope page, select Yes, I want to activate this scope now. A scope must be activated before it is allowed to assign clients IP addresses. If you do not want to activate it at this time, select No, I will activate this scope later. Click Next when done.
- Click Finish.
Scope Reservations
The purpose of DHCP is to automatically assign hosts connecting to your physical network an IP address. Which IP address they get depends on what has already been assigned and what is available. With reservations, on the other hand, we can ensure that a specific host always receives the same IP address.
Why would you do this instead of just assigning the host a static IP address? Well, this allows us to centrally assign IP addresses to all of our servers.
Host reservations use the MAC address of a client’s network interface. When the DHCP server sees this MAC address during a DHCP request, it matches it to an IP address in the reservation list and then assigns that IP address to the host. No other host may be assigned the IP address.
- In the DHCP console, from the left tree view expand the scope you want to add reservations to.
- Select and then right-click Reservations. When the context menu appears, click New Reservation…
FIG5 – Windows DHCP Scope Reservation - Give the reservation a name. You should probably use the hostname of the server you are reserving the address for.
Assign the IP address.
FIG6 – Windows DHCP New Reservation - Enter the MAC address of the servers network interface.
- Document the purpose of the reservation by entering a description.
- Under Support types, select either Both, DHCP or BOOTP.
Both The reservation will be used for both DHCP requests and BOOTP DHCP requests. DHCP The reservation will only apply to standard DHCP requests. BOOTP The reservation will only apply to BOOTP requests. - Click Add to add the new reservation.
Scope Options
Scope options are used to set additional network information when a host is assigned an IP address. This can be used to set the default gateway, DNS server, local time server (NTP), and many others.
You can find options for both Windows and Non-windows operating systems. For example, we can define the IP addresses of NIS servers for our Linux\Unix environment.
Options defined at the scope level will override options set at the DHCP server level.
- Launch the DHCP console from Server Manager.
- In the General tab, select the options you want to enable. These options will apply to all DHCP clients.
FIG7 – Windows DHCP Scope Options - In the Advanced tab, select the options you want to enable for a specific class of DHCP client. Classes can be used this to specifically target Linux servers, for example, so that only the get options set in the Advanced tab.
- When done, click OK.
Available Options
The following is a list of some of the options available for use. These can be found in both the General tab and Advanced tab of the Options dialog box.
002 Time offset | UTC time offset in seconds of the client. |
---|---|
003 Router | List of router IP addresses to be used as the default gateway. |
006 DNS Servers | IP address list of available DNS servers. |
015 DNS Domain Name | Sets the fully-qualified domain name suffix for the client. |
040 NIS Domain Name | Sets the NIS domain name to be used by the client. |
041 NIS Servers | List of IP addresses of NIS servers the client should connect to. |
042 NTP Servers | List of IP addresses of NTP servers the client should use for time syncs. |
If you wonder how basic network configuration is managed across your environment, today is your lucky day. You’ll learn how to connect to your Microsoft DHCP server and manage all of the common components from DHCP scopes, DHCP policies, DHCP reservations, and DHCP leases!
Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.
Prerequisites
This article is a tutorial. If you plan on following along step-by-step, you will need the following:
- A Microsoft DHCP Server in an Active Directory environment- This tutorial uses Windows Server 2019, but any server from 2008R2 onwards would work. The server is called dc01.stevesherry.com.
- An Active Directory account that is a member of the DHCP Administrators group or equivalent.
DHCP Scopes
At its simplest, a Microsoft DHCP server is a machine on a network that hands out IP addresses to clients. It ensures all clients receive IP addresses so they can communicate on the network. It does this through DHCP scopes.
A DHCP scope represents contains various components such as:
- Assignable IP addresses for a particular group of devices (address pools)
- A client’s DNS server and default gateway
- IPs to only assign to certain devices (DHCP reservations)
- Address pools (groups of assignable IP addresses)
The DHCP scope is a core element on a network and that allows you to configure network settings common to all of the clients on that network.
Creating a DHCP Scope via Server Manager
Let’s kick off this tutorial by learning how to add DHCP scopes to an existing DHCP server. For this first demo, you’re going to learn how to set up a DHCP scope via the Windows Server Manager.
Assuming you’re at the Windows desktop of a test DHCP server:
1. Click on your Start menu and type dhcpmgmt.msc to open the DHCP Microsoft Management Console (MMC).
2. Once the DHCP MMC opens, click on the dropdown to the left of the server name and then on IPV4.
Microsoft DHCP Server supports both IPv4 and IPv6 address allocation to clients. This tutorial will only focus on IPv4 scopes.
3. Right click on IPv4 and select New Scope to start the New Scope Wizard, and click Next on the introduction screen.
4. Provide a name of your choice for the Name and Description. This tutorial will create a scope for the company’s head office. Click Next when complete.
Scopes are commonly assigned to physical buildings or sometimes IP subnets.
5. Next, define an IP Address Range indicating the IP address range you’d like to assign to the DHCP server’s clients. The tutorial will ensure the first IP address allocated to clients will be 10.0.0.100 and the last IP address will be 10.0.0.200. These start and end IP addresses create the scope’s address pool which you’ll learn about later.
Also on this screen, enter a CIDR Length or Subnet mask which will be assigned to all clients.
It is common to deliberately leave the beginning and end of the address pool free to allow for any statically assigned addresses.
6. Click Next to skip past the Add Exclusions and Delay step.
If you know of one or more IP addresses that are already in use within the defined address range, an exclusion prevents the DHCP server from attempting to assign a particular IP address in its address pool.
7. For now, click Next to accept the default Lease Duration. You’ll learn a lot about DHCP leases later in this tutorial.
8. Leave the default setting of Yes, I want to configure these options now and click Next on the Configure DHCP Options step. You will configure various scope options shortly in this tutorial.
9. Next, provide an IP address of 10.0.0.1 for the Router (Default Gateway). Once the DHCP scope is available to clients, the DHCP server will hand out this IP address as the clients’ default gateway. The default gateway is the primary way clients can communicate with other networks or the Internet in general.
10. Since this tutorial is using an environment that has a DNS server located at 10.0.0.10, provide the IP address on the Domain name and DNS Servers step. This IP address will be handed out as the DNS client for DHCP clients to translate names into IP addresses.
The Parent domain should automatically populate based on the Active Directory domain the DHCP server is a member of.
11. If your environment still uses a WINS server, provide its IP address on the WINS Server step. This tutorial does not use one, so click Next to continue.
12. Finally, activate the new DHCP scope and make it available to clients by ensuring that Yes, I want to activate this scope now is selected. Then click Next to continue.
Once all of the above steps are followed, you should now see the new scope under IPv4 as shown below.
Creating a DHCP Scope with PowerShell
If you’re not a fan of the GUI or simply need to automate DHCP tasks, look no further than PowerShell. Let’s now cover the same process as just performed via the Server Manager, only this time with PowerShell.
Assuming you’re at the Windows desktop of a test DHCP server:
1. Open Windows PowerShell as administrator.
2. Run the Get-DhcpServerv4Scope
cmdlet to find all existing DHCP scopes.
As you’ll see in the below example, this server only has the scope that you’ve created using the GUI in the previous steps.
3. Run the Add-DhcpServerv4Scope
cmdlet to create a new DHCP scope. Since this cmdlet has many parameters, save time by defining each parameter in a PowerShell hashtable and using splatting to pass all parameters to the cmdlet.
This cmdlet will create a DHCP scope called Head Office Wireless Scope
that, when activated, will hand out IP addresses 10.1.0.100 – 10.1.0.200 with a subnet mask of 255.255.255.0 with a lease that expires after one day (day.hrs:mins:secs
).
# Create an IPv4 DHCP Server Scope
$HashArgs = @{
'Name' = 'Head Office Wireless Scope'; # This sets the name of the wireless scope
'Description' = 'Wireless Clients'; # This is the human-readable description of the scope
'StartRange' = '10.1.0.100'; # Specifies the starting IP address in the scope
'EndRange' = '10.1.0.200'; # Specifies the end IP address in the scope
'SubnetMask' = '255.255.255.0'; # Specifies the subnet mask of the scope
'State' = 'Active'; # Activates the scope
'LeaseDuration' = '1.00:00:00'; # Specifies the length of the lease duration
}
Add-DhcpServerv4Scope @HashArgs
4. Now, run Get-DhcpServerv4Scope
again to verify PowerShell successfully created the DHCP scope.
Piping output to the
Format-List
PowerShell cmdlet allows you to see each property name and it’s value rather than a truncated row.
Managing Scope Options
Once you’ve created a scope, you can modify any attribute you’d like. Microsoft DHCP has an area specifically called Scope Options which allows you to change some common DHCP attributes sent to DHCP clients.
Let’s now walk through the available scope options and cover their affect on your clients.
While in the DHCP MMC:
- Click on Scope Options under <server name> —> IPv4 —> Scope [X.X.X.X]. In the screenshot below, you can see the scope previously created. Here you can see the Router, DNS Servers, and DNS Domain Name that this scope will hand out to DHCP clients.
2. Right click on Scope Options and choose Configure Options to navigate to the Scope Options box to change these options.
3. Scroll down the available options under the General tab. You’ll see dozens of options that the DHCP server can assign to clients.
If you have a specific setting that is not available to you by default, you’ll need to follow the vendor’s specific information using the Advanced tab to create a custom Option.
4. Perhaps you forgot to add one of your DNS servers. Find the 006 DNS Servers option, enter it’s IP address, click Add, and OK. This tutorial will be using the IP address of 10.0.0.5.
Once you click OK, Windows will then validate if DNS services are available on your provided IP address.
5. Return to the main screen and review the Options pane. You’ll now see two IP addresses listed under 006 DNS Servers.
DHCP Leases
An important part of DHCP is the lease. A device is known to “lease” an IP address from a DHCP server for a certain period of time (lease time).
Network administrators typically configure DHCP servers to lease IP addresses based on different use cases. For example, for devices on a wired connection that rarely leave the network, administrators may assign a longer lease time like eight days. If the device never leaves the network, it’s not efficient to go through the lease renewal process.
On the other hand, if a wireless device roams on and off the network several times a week, administrators may assign a shorter lease period (12-24 hours) to save available IP addresses for other devices.
While in the DHCP console, you can find all current leases in <server name> —> IPv4 —> Scope [X.X.X.X] —> Address Leases as shown below.
Once on the Address Leases window, you’ll see each IP address that the DHCP server has assigned along with the Lease Expiration date.
Setting the Microsoft DHCP Lease Period
Let’s now discover how to set the DHCP lease period at the server level for DHCP clients.
While still in the DHCP console on the DHCP server:
1. Find the scope containing the IP address pool you’d like to look at, right-click on the scope name, and select Properties.
2. Within the Properties window, you’ll now see a Lease duration for DHCP clients. This setting is the DHCP lease time for all IP addresses in that scope.
The default DHCP lease period on Microsoft DHCP servers is eight days, but it can be updated to any period of time to suit the business needs.
3. Click Cancel to close the Properties box.
Finding Assigned DHCP Lease Times
DHCP services can only assign one IP address per device. How does the DHCP server know when it can re-use an IP address in the pool? The DHCP lease time.
If a device doesn’t renew its dynamically assigned IP address within the lease time, the lease expires and is available to other devices to lease.
How do you actually discover the lease time on a device? Unfortunately, each operating system (OS) has a different way of exposing the DHCP lease time. This tutorial will cover how to determine lease time on Windows 10.
In Windows 10, you see your DHCP lease time on the command-line either with the command prompt (cmd.exe) or PowerShell. This tutorial assumes you are an IT pro so let’s use PowerShell.
To find a Windows DHCP client’s lease time, on the Windows client console, open Windows PowerShell and run the ipconfig /all
command.
You’ll see the time the lease was made (Lease Obtained) and when it expires (Lease Expires). The Lease Obtained field is the exact time the DHCP server assigned the IP address to this device. The Lease Expires field indicates the time the device will ask the DHCP server to renew its lease.
Subtract the Lease Expires value from the Lease Obtained value and you have your DHCP lease time.
DHCP Address Pools
Once you’ve configured the scope, you already have an address pool. The address pool is the range of IP addresses the DHCP server will assign to clients in a lease. Let’s navigate through the address pool already set up.
Updating the Address Pool
IP address scopes are not fixed in stone. It’s inevitable that after some time you’ll need to expand the address pool to allow more devices to connect to your network. Rather than creating a new address pool, it’s often easier to expand an existing pool. To do that:
1. Right click on <server name> —> IPv4 —> Scope [X.X.X.X] and click on Properties to open the Scope Properties configuration wizard.
2. Update the fields to increase the range of IP addresses for your existing address pool so that more addresses are available for any future allocation. Once complete, click OK.
3. Click on <server name> —> IPv4 —> Scope [X.X.X.X] —> Address Pool to bring up the address pool. Notice below that it now shows the expanded Address Pool in the scope.
Adding Exclusion Ranges to the Address Pool
Imagine that you need to create a small list of IP addresses within the address pool that are not assigned to any new devices on the network. Exclusion ranges are how you’d achieve this.
Assuming that you still have the DHCP console open:
1. Click on <server name> —> IPv4 —> Scope [X.X.X.X] —> Address Pool to bring up the address pool.
2. Right-click on Address Pool and click on New Exclusion Range to open the Add Exclusion wizard.
3. Complete the fields to create a small range of IP addresses within your existing address pool that will not be included in any future allocation of leases. Once complete, click Add.
4. Back on the DHCP console, refresh the screen and note that the exclusion is now in place.
At this point, whenever a new device connects to the network, your DHCP server will not lease an address from within this exclusion range.
DHCP Reservations
IP addresses are, by their nature, dynamic. Most of the time this is OK as you typically don’t care what the IP address of your PC is. Occasionally you’ll need to manually specify the address of a device such as an admin laptop or a printer.
When you need to statically assign an IP address to a particular device, use a DHCP reservation.
Adding Reservations
Let’s start out by adding a reservation to a scope previously created. While in the DHCP console on the DHCP server:
1. Select <server name> —> IPv4 —> Scope [X.X.X.X] —> Reservations to open the Reservations window. You’ll see no reservations exist.
2. Right-click on Reservations and then choose New Reservation to open the New Reservation input box.
3. Complete the fields with details that are relevant to a device you’d like to assign a “static” IP address to.
- The Reservation name – This name is commonly as a hostname for the device or other identifying attribute.
- The IP address to reserve for the device.
- The MAC address of the device
Find the MAC address of a device from either the label that is on the back, or by using these methods.
- The Description – Be sure to make sense here so that other administrators can understand what this reservation is for.
Once complete, click Add.
4. Back on the DHCP console, refresh the screen and note that the reservation is now in place.
At this point, when the device that has the MAC address you’ve provided in the reservation goes through its DHCP lifecycle, it will be assigned the expected reserved IP address.
Removing Reservations
As part of the general lifecycle of devices within your organization, you’ll occasionally have to retire old devices, some of which will have DHCP reservations.
Assuming you’re still in the DHCP console, removing DHCP reservation requires a right click on the reservation and clicking Delete.
DHCP Policies
Previously, you learned how to set reservations by MAC address. Although reservations are useful, they don’t allow you to assign addresses or specific scope options based on other criteria. Using a DHCP policy, you can define various conditions a client must meet to assign an IP address.
Using a DHCP policy, you can assign a specific category of devices a different DNS server, default gateway, or TFTP server, for example.
To create a DHCP policy:
1. Right click <server name> —> IPv4 —> Scope [X.X.X.X] —> Policies and click on New Policy to open the Policy configuration window.
2. Complete the fields with details of the Policy Name and a Description for the policy. Click Next, once complete.
3. Click on the Criteria dropdown and notice the many conditions you can check for on a client. For this tutorial, select MAC Address and add a relevant Value, selecting Wildcard.
Click Add, and then OK to move along.
4. Either Add another condition for the policy or click Next to continue.
5. Next, add a subset of IP addresses from within your existing range. The DHCP server will assign devices matching the conditions defined earlier an IP address from this range. Once complete, click Next.
6. Now it’s time to define the options the client will receive if it meets the condition. For this tutorial, select 003 Router to modify the default gateway clients matching the condition will receive.
Enter an IP address for the new gateway, click Add and then Next.
7. Review the screen and confirm that the details are correct. Click Finish to close the wizard.
8. Refresh the screen to confirm that the new policy is in place.
Conclusion
In this article, you’ve covered a lot of ground when it comes to DHCP. You’ve learned how to set up DHCP scopes and everything that comes with them. You also learned how DHCP assigns IP addresses and other information to clients.
Armed with all of this new information, you can now confidently tackle DHCP like a champion. How are you planning on using this knowledge?
Данная статья описывает процедуру установки и настройки DHCP сервера на базе Windows Server 2019. В статье описаны особенности установки и настройки DHCP роли, создания областей DHCP, настройки их параметров и резервации статических адресов. Мы рассмотрим как привычный способ настройки параметров DHCP сервера через графическую консоль, так и настройку DHCP из командной строки PowerShell.
Протокол DHCP (Dynamic Host Configuration Protocol) используется для автоматического назначения сетевых настроек (IP адрес, маска подсети, шлюз, DNS сервера и т.д.) устройствам в вашей сети (компьютеры, ноутбуки, сканеры, принтеры и т.д.). Также DHCP сервер позволяет более эффективно использовать адресное пространство, избегать конфликта IP адресов в сети и централизованно управлять сетевыми параметрами на клиентских устройствах.
Содержание:
- Установка роли DHCP сервера в Windows Server 2019/2016
- Настройка DHCP областей в Windows Server
- Резервация IP адресов на DHCP сервере
- Настройка и управление DHCP сервером с помощью PowerShell
Установка роли DHCP сервера в Windows Server 2019/2016
В этом примере мы установим DHCP сервер на хосте с Windows Server 2019 и IP адресом 192.168.13.4. Вы можете использовать как Server Core версию, так и Full GUI. В маленькой инфраструктуре допустимо устанавливать DHCP сервер на сервер с ролью контроллера домена Active Directory.
Обязательно назначьте статический IP адрес серверу с ролью DHCP сервер. При установке роли DHCP из консоли PowerShell на сервере с автоматическим получением IP адреса появляется предупреждение:
Configure at least one static IP address on your computer before installing DHCP. WARNING: The following recommended condition is not met for DHCP: No static IP addresses were found on this computer. If the IP address changes, clients might not be able to contact this server. Please configure a static IP address before installing DHCP Server.
Установить роль DHCP Server можно из консоли Server Manager (Add Roles and Features -> Server Roles).
После установки роли DHCP роли нужно выполнить Post-Deployment Configuration. Для этого в консоли Server Manager щелкните по уведомлению и выберите Complete DHCP configuration.
Вам будет предложено аутентифицировать новый DHCP сервер в Active Directory (экран Authorization). Для авторизации DHCP сервера в AD учетная запись должна состоять в доменной группе Enterprise Admins.
Если у вас нет прав на авторизацию DHCP в AD, вы можете указать, чтобы ваш DHCP сервер запускался без проверки авторизации в домене:
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DHCPServer\Parameters" -Name DisableRogueDetection -Value 1 -Force
Также вы можете установить и настроить DHCP роль в Windows Server из консоли PowerShell.
Установка роли DHCP:
Install-WindowsFeature DHCP –IncludeManagementTools
Проверьте, что роль и инструменты управления RSAT-DHCP установлены:
Get-WindowsFeature -Name *DHCP*| Where Installed
Авторизуйте DHCP сервер в Active Directory (укажите DNS имя сервера и IP адрес, который будет использоваться DHCP клиентами):
Add-DhcpServerInDC -DnsName hq-dc01.contoso.com -IPAddress 192.168.13.4
Создайте локальные группы безопасности DHCP сервера:
Add-DhcpServerSecurityGroup
Чтобы Server Manager перестал показывать уведомление о том, что DHCP роль требует настройки, выполните команду:
Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\ServerManager\Roles\12 -Name ConfigurationState -Value 2
Перезапустите службу DHCPServer:
Restart-Service -Name DHCPServer -Force
База данных и логи DHCP сервера находятся в каталоге
%systemroot%\system32\dhcp
.
- dhcp.mdb — файл базы данных сервера DHCP’;
- j50.log – транзакционный журнал (используется при восстановлении конфигурации DHCP);
- j50.chk — файл контрольной точки;
- tmp.edb — временный рабочий файл DHCP-сервера.
Настройка DHCP областей в Windows Server
После установки роли DHCP вам нужно создать DHCP области (Scopes), которые описывают диапазоны IP адресов и другие настройки, выдающиеся сервером клиентам.
Для управления сервером DHCP используется консоль dhcpmgmt.msc (вы можете управлять DHCP сервером локально или с удаленного компьютера с установленным RSAT). Запустите консоль DHCP, разверните ваш сервер -> IPv4.
Чтобы создать новую область выберите New Scope.
Укажите название DHCP области.
Укажите диапазон IP адресов, который будет выдаваться этой областью и маску сети. В этом примере я хочу использовать эту DHCP область для обслуживания подсети 192.168.100.0/24. В рамках этой сети DHCP сервером будет назначаться динамические IP адреса из диапазона 192.168.100.50 — 192.168.100.250. В следующем окне можно добавить исключения в этот диапазон (Add Exclusions and Delay).
Далее нужно указать длительность аренды (Lease Duration) IP адреса DHCP клиентом (по умолчанию 8 дней, менять без особой необходимости не нужно).
Укажите, что вы хотите настроить дополнительный параметры DHCP области.
.
Укажите IP адрес шлюза в подсети, который должен назначаться клиентам (в нашем примере это 192.168.100.1).
Затем укажите имя домена и адреса DNS серверов, которые будут назначены клиентам DHCP.
Осталось активировать DHCP область (разрешить ей обслуживать клиентов).
DHCP сервер может выдавать клиентам различный настройки (кроме IP адреса). Для этого используются Scope Options.
В Windows Server DHCP можно настроить глобальные настройки области или Scope Options для каждой области.
Ранее мы уже настроили три опции области:
-
003 Router
-
006 DNS Server
-
015 DNS Domain Name
Можно добавить и другие опции (NTP сервера, PXE и т.д.).
В разделе Server Options DHCP сервера можно настроить глобальные опции, которые будут наследуются всеми областями. Но вы можете переопределить глобальные настройки в настройках каждой области (опции области имеют приоритет над опциями сервера).
Один DHCP сервер может обслуживать сотни удаленных подсетей и VLAN. Поэтому вы можете создать на нем несколько областей. Главное, чтобы в каждой из подсетей был настроен ретранслятор (DHCP relay agent), который пересылает широковещательные DHCP-запросы на указанный DHCP сервер. В терминах Cisco DHCP ретранслятор называется ip helper. Вы можете настроить DHCP Relay даже на Windows Server.
Протокол DHCP в качестве транспорта использует протокол UDP. Пакеты от клиента к серверу передаются по порту 67 UDP, обратно через UDP 68
Резервация IP адресов на DHCP сервере
По умолчанию DCHP сервер выдает клиентам динамические адреса. Это означает что IP адрес у любого клиента может меняться. Если вы хотите, чтобы определенные устройства всегда получали от DHCP сервера один и тот же адрес, вы можете его зарезервировать (например, для сетевых принтеров, которые настроены у пользователей).
Для DHCP резервации выберите область и перейдите в секции Reservation. В меню выберите New Reservation.
При создании резервации нужно указать IP адрес, который нужно сохранить за клиентом и его MAC адрес (уникальное значение). MAC адрес в Windows можно получить из результатов команды
ipconfig /all
или с помощью PowerShell
get-netadapter|select name,macaddress
). Опционально можно указать имя и описание устройства.
Также вы можете зарезервировать текущий динамический адрес за устройством, найдя его в разделе Address Leases. Щелкните по устройству и выберите Add to Reservation.
Настройка и управление DHCP сервером с помощью PowerShell
Все операции по настройке и управлению DHCP сервером на Windows Server 2019/2016 можно выполнять из консоли PowerShell. Рассмотрим основные команды управления DHCP. Для этого используется модуль DHCPServer. Импортируйте модуль в сессию:
Import-Module DHCPServer
Вывести полный список командлетов в моделе DHCP можно так:
Get-Command -Module DHCPServer
Следующая команда выведет список авторизованных DHCP серверов в Active Directory:
Get-DhcpServerInDC
Вывести список DHCP областей на указанном сервере:
Get-DhcpServerv4Scope –ComputerName msk-dhcp1
Если нужно показать все параметры области (Delay, Description, Name и т.д.):
Get-DhcpServerv4Scope –ComputerName msk-dhcp1| FL *
Если нужно отобразить данные о IPv6 областях:
Get-DHCPServerv6Scope
Получить настройки для конкретной области:
Get-DhcpServerv4Scope –ComputerName msk-dhcp1 –ScopeID 10.10.1.0
Создадим новую (неактивную) область с диапазоном адресов с 192.168.113.50 до 192.168.113.250:
Add-DhcpServerv4Scope -Name “Brahch1 192.168.113.0” -StartRange 192.168.113.50 -EndRange 192.168.113.250 -SubnetMask 255.255.255.0 -State InActive
Настроить следующие параметры DHCP сервера: DNS сервер, домен и адрес шлюза по-умолчанию:
Set-DhcpServerv4OptionValue -ScopeID 192.168.113.0 -DnsDomain contoso.com -DnsServer 192.168.13.4 -Router 192.168.113.1
Добавить исключения в DHCP область:
Add-DhcpServerv4ExclusionRange -ScopeID 192.168.113.0 -StartRange 192.168.113.90 -EndRange 192.168.113.100
Активировать DHCP область:
Set-DhcpServerv4Scope -ScopeID 192.168.113.0 -State Active
Для удобства можно использовать такую команду PowerShell при создании новой области:
$HashArgs = @{
'Name' = 'EKB Office Scope';
'Description' = 'workstations';
'StartRange' = '192.168.140.10';
'EndRange' = '192.168.140.200';
'SubnetMask' = '255.255.255.0';
'State' = 'Active';
'LeaseDuration' = '1.00:00:00';
}
Add-DhcpServerv4Scope @HashArgs
Опции для DHCP сервера добавляется так (к примеру, WPAD):
Add-DhcpServerv4OptionDefinition -ComputerName msk-dhcp1 -Name WPAD -OptionId 252 -Type String
Вывести список настроенных опций DHCP сервера можно так:
Get-DHCPServerv4OptionValue -ComputerName msk-dhcp1 | Format-List
Выведем список настроенных параметров зоны:
Get-DHCPServerv4OptionValue -ComputerName msk-dhcp1 -ScopeId 10.10.1.0 | Format-List
Показать текущий список арендованных адресов для области 10.10.1.0:
Get-DHCPServerv4Lease -ScopeId 10.10.1.0 -ComputerName msk-dhcp1
Создать DHCP резервацию для клиента, которому назначен динамический IP адрес 10.10.1.88 (конвертировать выданный адрес в зарезервированный):
Get-DhcpServerv4Lease -ComputerName msk-dhcp1 -IPAddress 10.10.1.88| Add-DhcpServerv4Reservation -ComputerName msk-dhcp1
Можно массово зарезервировать IP адреса для компьютеров по списку из csv файла. Для этого создайте текстовый файл в формате:
ScopeId,IPAddress,Name,ClientId,Description 10.10.1.0,10.10.1.88,Client1,ba-ab-5c-3d-4e-6f,Reservation PC-msk-s1 10.10.1.0,10.10.1.89,Client2,ba-ab-5c-5d-2e-3f,Reservation PC-msk-s2
Сохраните файл с именем
c:\dhcp\DHCPReservations.csv
и запустите следующую команду, которая импортирует данные из csv файла и создаст DHCP резервации для клиентов:
Import-Csv –Path c:\dhcp\DHCPReservations.csv | Add-DhcpServerv4Reservation -ComputerName msk-dhcp1
Отключить область на DHCP сервере:
Set-DhcpServerv4Scope -ComputerName msk-dhcp1-ScopeId 10.10.1.0-State InActive
Удалить область с DHCP сервера:
Remove-DHCPServerv4Scope -ComputerName msk-dhcp1-ScopeId 10.10.1.0 -Force
Возможно получить статистику DHCP сервера (количество областей, резерваций, процент использования адресов и пр.).
Get-DhcpServerv4Statistics -ComputerName msk-dhcp1
Аналогичная информация для конкретной области может быть получена с помощью командлета Get-DhcpServerv4ScopeStatistics.
Конфигурацию DHCP сервера можно экспортировать в указанный XML файл с помощью команды:
Export-DHCPServer -ComputerName msk-dhcp1 -File C:\dhcp\dhcp-export.xml
Совет. Заданием с такой командой в планировщике задач можно реализовать регулярное резервное копирование конфигурации DHCP сервера.
В дальнейшем эти настройки DHCP сервера можно импортировать (перенести) на другой DHCP сервер:
Import-DHCPServer -ComputerName msk-dhcp2 -File C:\dhcp\dhcp-export.xml -BackupPath C:\dhcpbackup\
Use PowerShell to create dynamically assigned ranges of IP addresses using DHCP scopes.
What is a DHCP scope?
Per TechNet, a DHCP scope “is the consecutive range of possible IP addresses that the DHCP server can lease to clients on a subnet. Scopes typically define a single physical subnet on your network to which DHCP services are offered. Scopes are the primary way for the DHCP server to manage distribution and assignment of IP addresses and any related configuration parameters to DHCP clients on the network.”
Let’s say you have three subnets on your local network, 192.168.1.0/24, 192.168.2.0/24, and 192.168.3.0/24. The first subnet, 192.168.1.0/24, is a server and network management subnet where all IPs are statically assigned. For this subnet, you would not need to configure a DHCP scope.
For the other subnets, 192.168.2.0/24 is for your wired clients and 192.168.3.0/24 is for your wireless clients. These clients will connect and disconnect to the network throughout the day and week. For these subnets, you would configure a DHCP scope to handle the automatic assignment of IP address leases to these clients.
Creating a DHCP scope using PowerShell
In our previous post we installed the DHCP Server role and authorized it in our Active Directory domain. Building off of that configuration, we will create the DHCP scopes for 192.168.2.0/24 and 192.168.3.0/24.
For 192.168.2.0/24, here are the requirements for the DHCP scope:
- Assignable addresses should be between 192.168.2.21 and 192.168.2.250.
- The lease duration should be the default of 8 days.
- DHCP clients should be assigned 192.168.2.1 as their default gateway.
- DHCP clients should be assigned 192.168.1.11 as their DNS server.
- A TFTP server, 192.168.1.10, needs to be provided in the event a VoIP phone is connected.
Create the scope
We begin by creating the base IPv4 scope. Note the example below uses a technique called splatting to make the parameter set more readable. We will use the Add-DhcpServerv4Scope cmdlet:
# Create an IPv4 DHCP Server Scope $HashArgs = @{ 'Name' = '002_WiredClients'; 'Description' = 'Wired Clients'; 'StartRange' = '192.168.2.21'; 'EndRange' = '192.168.2.250'; 'SubnetMask' = '255.255.255.0'; 'State' = 'Active'; } Add-DhcpServerv4Scope @HashArgs
Set DHCP scope options
Now that we have created the scope, we can set the DHCP scope options. This includes things like (but are not limited to) the default gateway (aka ‘Router’), DNS servers, a domain name, and more.
Create a new server option
VoIP phones (e.g. a Cisco phone) requires this option be configured in order for the phone to get its configuration. By default, DHCP option 150 (TFTP server) is not available on a Windows DHCP Server. This option definition needs to be created.
# Create option definition for TFTP Server Add-DhcpServerv4OptionDefinition -OptionId 150 -Type IPv4Address -Name "TFTP Server"
Set DHCP scope options
Now that we have created the scope and defined the additional option for a TFTP server, we can set the options for our scope using Set-DhcpServerv4OptionValue. Note that we use the ScopeId parameter to only set these options for this particular scope. If we were to omit this parameter, the option would be set at the server level, and would inherited by all scopes if they didn’t have the option explicitly set at the scope level.
# Set DHCP scope options $HashArgs = @{ 'ScopeId' = '192.168.2.0'; 'DnsServer' = '192.168.1.11'; 'DnsDomain' = 'lab.thinkpowershell.com'; 'Router' = '192.168.2.1'; } Set-DhcpServerv4OptionValue @HashArgs # Set TFTP option Set-DhcpServerv4OptionValue -ScopeId 192.168.2.0 -OptionId 150 -Value 192.168.1.10
Create a DHCP Scope with a short lease duration
We have created the DHCP scope for wired clients, and now we want to create the scope for wireless clients. In our scenario, we know that we may see many different wireless clients in a given week, but most clients are only around for a single day at a time. I could expand the address range I allow for clients, but instead I am going to shorten the default lease duration to 1 day, so that addresses are only committed to a client for 24 hours at a time. I can use the LeaseDuration parameter and the format day.hrs:mins:secs to set that requirement.
# Create an IPv4 DHCP Server Scope $HashArgs = @{ 'Name' = '003_WirelessClients'; 'Description' = 'Wireless Clients'; 'StartRange' = '192.168.3.21'; 'EndRange' = '192.168.3.250'; 'SubnetMask' = '255.255.255.0'; 'LeaseDuration' = '1.00:00:00' # day.hrs:mins:secs 'State' = 'Active'; } Add-DhcpServerv4Scope @HashArgs # Set DHCP scope options $HashArgs = @{ 'ScopeId' = '192.168.3.0'; 'DnsServer' = '192.168.1.11'; 'DnsDomain' = 'lab.thinkpowershell.com'; 'Router' = '192.168.3.1'; } Set-DhcpServerv4OptionValue @HashArgs
Copy DHCP scopes from an existing Windows DHCP Server
If you are already using a Windows DHCP server in your environment but are migrating to a new DHCP server, you can use PowerShell to copy the configured scopes from your old server to your new server:
# Copy DHCP scopes from one DHCP server to another Get-DhcpServerv4Scope -ComputerName OldDhcpServer | Add-DhcpServerv4Scope -ComputerName NewDhcpServer
Next Steps: Creating DHCP Reservations
DHCP is great for being able to avoid statically assigning IP addresses to devices, but how do you take advantage of the dynamic capability of DHCP, while still providing certain types of devices with a consistent, predictable address? In my next post, we will cover creating and migrating DHCP reservations.
A DHCP scope is a range of IP addresses that a DHCP server can assign to clients. Once you’ve installed the DHCP role on your Windows Server, the next step is to configure your DHCP scopes. This guide will provide simple instructions on how to do this.
1. First, you need to open the DHCP Manager. You can do this by clicking on the Start Menu, typing Server Manager into the search box, and clicking on Tools then clicking on Computer Management.
2. On the left panel of the Computer Management window, you have many options. Click on the drop-down arrow next to Services and Applications. Then you will see your server, proceed to click the drop-down arrow next to it.
3. Right-click on IPv4 and then click on New Scope… from the drop-down menu. This will open the New Scope Wizard to guide you through the process.
4. Once the New Scope Wizard opens, click Next on the welcome page.
5. On the next page, you’ll be asked to give your new scope a name and an optional description. Choose a name that easily identifies the scope, then click Next.
6. Here, you’ll need to enter the range of IP addresses you want the DHCP server to assign. You’ll need to input the Start IP address, End IP address, and Subnet mask. After filling out these fields, click Next.
The IP addresses in the photo are just an example, please input the range that you would like the DHCP server to assign.
7. If there are any IP addresses in the range you specified that you don’t want the DHCP server to assign, you can exclude them here. You can also set a delay for the DHCP server. Once you’ve done this, click Next.
8. On the Lease Duration page, you can set how long a client can use an IP address before it’s returned to the pool. The default setting is 8 days, but you can change this according to your needs. Click Next when you’re ready.
9. The next few pages will ask you to configure DHCP options like default gateway, DNS server, and WINS server. If you’re not sure what to input here, you can just click Next to accept the default options. For the purposes of this guide, we will skip these steps and leave them as default.
10. Finally, review the summary of your new scope. If everything is correct, click Finish to complete the wizard.
Congratulations! You have successfully configured a DHCP scope on your Windows Server. You can now assign IP addresses to clients in your network. If you have different networks, you can repeat the process to create more scopes.