You get a bonus - 1 coin for daily activity. Now you have 1 coin

DHCP - Dynamic Host Configuration Protocol - Operational Algorithm

Lecture



DHCP (born Dynamic Host Configuration Protocol - Dynamic Host Configuration Protocol ) is a network protocol that allows computers to automatically obtain an IP address and other parameters necessary for working on a TCP / IP network. This protocol works according to the client-server model. For automatic configuration, the client computer at the network device configuration stage accesses the so-called DHCP server and receives the necessary parameters from it. The network administrator can set the range of addresses that the server distributes to computers. This avoids manual configuration of network computers and reduces errors. DHCP is used on most TCP / IP networks.

DHCP is an extension of the BOOTP protocol that was previously used to provide diskless workstations with IP addresses when they are loaded. DHCP maintains backward compatibility with BOOTP.

Content

  • 1. History
  • 2 Distribution of IP Addresses
  • 3Option DHCP
    • 3.1 Supplier Identification.
  • 4 Protocol device
    • 4.1 Structure of DHCP messages
    • 4.2 Example of the process of obtaining an address
      • 4.2.1 DHCP Discovery
      • 4.2.2 DHCP Offer
      • 4.2.3 DHCP Request
      • 4.2.4 DHCP Confirmation
      • 4.2.5 Message Type
    • 4.3Other DHCP messages
      • 4.3.1 DHCP Rejection
      • 4.3.2 Release DHCP
      • 4.3.3 DHCP Information
  • 5 Realizations
  • 6Notes
  • 8Links

Story

The DHCP protocol standard was adopted in October 1993. The current version of the protocol (March 1997) is described in RFC 2131. The new version of DHCP, intended for use in the IPv6 environment, is called DHCPv6 and defined in RFC 3315 (July 2003).

IP address allocation

DHCP provides three methods for allocating IP addresses:

  • Manual distribution. With this method, the network administrator assigns a specific IP address to the hardware address (for Ethernet networks, this is the MAC address) of each client computer. In fact, this method of address allocation differs from manual configuration of each computer only in that address information is stored centrally (on a DHCP server), and therefore it is easier to change them if necessary.
  • Automatic distribution. With this method, each computer is allocated for permanent use an arbitrary free IP address from the range defined by the administrator.
  • Dynamic distribution. This method is similar to automatic distribution, with the exception that the address is given to a computer not for permanent use, but for a certain period. This is called a rental address . Upon expiration of the lease, the IP address is again considered free, and the client is obliged to request a new one (which, however, may be the same). In addition, the client himself can refuse the received address.

Some DHCP service implementations are capable of automatically updating DNS records corresponding to client computers when new addresses are allocated to them. This is done using the DNS update protocol described in RFC 2136.

1.2. Formulation of the problem

DHCP is intended to provide DHCP clients with the configuration parameters described in Host Requirements RFC. After receiving the necessary parameters via DHCP, the DHCP client must be ready to exchange packets with any other computer on the Internet. The TCP / IP stack options provided by DHCP are listed in Appendix A. Not all of these parameters are necessary for the initial initialization of the client. The client and server can agree on a list of required parameters.

DHCP allows, but does not require, configuration of client parameters that are not directly related to the IP protocol. DHCP does not contact the DNS system to register the address [12, 13]. DHCP cannot be used to configure routers.

1.3. Terminology

The following definitions apply in this document:

DHCP client A DHCP client is a computer connected to the Internet that uses DHCP to obtain configuration parameters, such as a network address.
DHCP server A DHCP server is a computer connected to the Internet that sends configuration parameters to a DHCP client.
BOOTP forwarding agent A BOOTP forwarding agent is a computer connected to the Internet or a router that communicates between a client and a DHCP server. DHCP is designed to be compatible with BOOTP protocol specifications.
Binding Pairing (binding) is a set of configuration parameters, including, at least, the IP address assigned to the DHCP client. Pairing is managed by DHCP servers.

1.4. Goals

Below is a list of the main tasks of DHCP.

o DHCP is a mechanism, not a policy. DHCP should be managed by local system administrators by setting the desired configuration parameters.
o Clients should not require manual configuration. Each client must be able to read the local configuration parameters.
o Networks should not require manual configuration for individual clients. Under normal circumstances, the network administrator should not enter any individual client configuration parameters.
o DHCP does not require a separate server for each subnet.
o The DHCP client should be ready to receive multiple responses to the request for configuration parameters. To increase reliability and speed, you can use multiple DHCP servers serving overlapping areas of the network.
o DHCP must coexist with computers that are manually configured.
o DHCP must be compatible with the BOOTP agent operation logic described in RFC-951 and RFC-1542 [21].
o DHCP should service existing BOOTP clients.

DHCP should:

o Ensure that any specific network address is not used by more than one DHCP client at the same time.
o Support DHCP client configuration when starting restarting a DHCP client. The DHCP client should, with each request to the extent possible, be assigned the same set of configuration parameters (for example, a network address).
o Maintain the DHCP client configuration when the server is restarted, and, to the extent possible, the same set of configuration parameters should be assigned to the DHCP client.
o Allows you to automatically assign configuration settings to new clients to avoid manual configuration.
o Maintain a fixed or permanent assignment of configuration parameters for a given client.

DHCP options

In addition to the IP address, DHCP can also inform the client of additional parameters necessary for normal operation on the network. These options are called DHCP options . A list of standard options can be found in RFC 2132.

Options are variable-length octet strings. The first octet is the option code, the second octet is the number of the following octets, the remaining octets depend on the option code.

For example, the option “DHCP Message Type” when sending a message “Offer” will look like this: 0x35,0x01,0x02, where 0x35 is the code of the option “DHCP Message Type”, 0x01 means that only one octet follows, 0x02 means “ Offer ”.

Some of the most commonly used options are:

  • The default IP address of the router
  • Subnet mask;
  • DNS server addresses;
  • DNS domain name.

Some software providers may define their own advanced DHCP options.

The following tables list the available DHCP options as specified in RFC2132:

RFC1497 software vendor extensions.

Code Title Length Note

0

Pad

0 octets

  Used to complement other options so that they align to the word boundary.

one

Subnet mask

4 octets

  Must be sent after the “router” option (option 3) if both are enabled.

2

Time offset

4 octets

3

Router

multiple to 4 octets

  Available routers should be listed in order of preference.

four

Time server

multiple to 4 octets

  Available servers for synchronization should be listed in order of preference.

five

Name Server

multiple to 4 octets

  Available IEN 116 - server names must be listed in order of preference.    

6

Domain Name Server

multiple to 4 octets

Available DNS servers should be listed in order of preference.

7

Log server

multiple to 4 octets

Available log-servers should be listed in order of preference.

eight

Cookie Server

multiple to 4 octets

9

LPR Server

multiple to 4 octets

ten

Impress Server

multiple to 4 octets

eleven

Resource Location Server

multiple to 4 octets

12

Host name

at least 1 octet

13

Boot file size

2 octets

  The length of the boot image in 4-kilobyte blocks.

14

Merit dump file

at least 1 octet

  Path to the storage of emergency dumps.

15

Domain Name

at least 1 octet

sixteen

Swap Server

4 octets

17

Root path

at least 1 octet

18

Extensions path

at least 1 octet

255

End

0 octets

Used to mark the end of a field.

Parameters of client IP level.

Code Title Length Note

nineteen

IP Forwarding Enable / Disable

1 octet

20

Non-Local Source Routing Enable / Disable

1 octet

21

Policy filter

Multiple to 8 octets

22

Maximum Datagram Reassembly Size

2 octets

23

Default IP Time-to-live

1 octet

24

Path MTU Aging Timeout

4 octets

25

Path MTU Plateau Table

Multiple 2 octets

Interface parameters IP-level.

Code Title Length Note

26

Interface MTU

2

27

All Subnets are Local

one

28

Broadcast Address

four

29

Perform Mask Discovery

one

thirty

Mask Supplier

one

31

Perform Router Discovery

one

32

Router Solicitation Address

four

33

Static route

Multiple to 8 octets

Interface level communication options.

Code Title Length Note

34

Trailer Encapsulation Option

one

35

ARP Cache Timeout

four

36

Ethernet encapsulation

one

TCP parameters

Code Title Length Note

37

TCP Default TTL

one

38

TCP Keepalive Interval

four

39

TCP Keepalive Garbage

one

Parameters of services and applications.

Code Title Length Note

40

Network Information Service Domain

at least 1 octet

41

Network Information Servers

multiple to 4 octets

42

Network Time Protocol Servers

multiple to 4 octets

43

Vendor Specific Information

at least 1 octet

44

NetBIOS over TCP / IP Name Server

multiple to 4 octets

45

NetBIOS over TCP / IP Datagram Distribution Server

multiple to 4 octets

46

NetBIOS over TCP / IP Node Type

one

47

NetBIOS over TCP / IP Scope

at least 1 octet

48

X Window System Font Server

multiple to 4 octets

49

X Window System Display Manager

multiple to 4 octets

64

Network Information Service + Domain

at least 1 octet

65

Network Information Service + Servers

multiple to 4 octets

68

Mobile IP Home Agent

multiple to 4 octets

69

Simple Mail Transport Protocol (SMTP) Server

multiple to 4 octets

70

Post Office Protocol (POP3) Server

multiple to 4 octets

71

Network News Transport Protocol (NNTP) Server

multiple to 4 octets

72

Default World Wide Web (WWW) Server

multiple to 4 octets

73

Default Finger Server

multiple to 4 octets

74

Default Internet Relay Chat (IRC) Server

multiple to 4 octets

75

Streettalk server

multiple to 4 octets

76

StreetTalk Directory Assistance (STDA) Server

multiple to 4 octets

DHCP extensions.

Code Title Length Note

50

Requested IP address

four

51

IP address Lease Time

four

52

Option Overload

one

53

DHCP Message Type

one

54

Server identifier

four

55

Parameter Request List

at least 1 octet

56

Message

at least 1 octet

57

Maximum DHCP Message Size

2

58

Renewal (T1) Time Value

four

59

Rebinding (T2) Time Value

four

60

Vendor class identifier

at least 1 octet

61

Client-identifier

minimum 2 octets

66

TFTP server name

at least 1 octet

67

Bootfile name

at least 1 octet

Supplier Identification.

An option exists to define the provider and functionality of the DHCP client. The information is represented by a string of variable length consisting of characters or octets that have the value specified by the DHCP client provider. One of the methods allows the DHCP client to notify the server that it uses a certain type of low-level software or firmware to fill in the Vendor Class Identifier (VCI) option (option 60). This method allows you to distinguish between requests from client machines and processes. The VCI option value gives the DHCP server a hint about any additional information that needs to be sent to the client in response.

Protocol device

DHCP is a client-server protocol, that is, a DHCP client and a DHCP server are involved in its work. Data transfer is performed using the UDP protocol. By default, requests from the client are made on port 67 to the server, the server in turn responds to port 68 to the client, issuing an IP address and other necessary information, such as a network mask, a router and DNS servers.

DHCP message structure

All DHCP messages are divided into fields, each of which contains certain information. All fields except the last (DHCP options fields) have a fixed length.

Field Description Length (in bytes)
op Message type For example, the values ​​can be: BOOTREQUEST (1, request from client to server) and BOOTREPLY (2, response from server to client). one
htype Type of hardware address. Valid values ​​for this field are defined in RFC1700 Assigned Numbers. For example, for a 10 Mbps Ethernet MAC address, this field is 1. one
hlen The length of the hardware address in bytes. For Ethernet MAC-address - 6. one
hops The number of intermediate routers (called DHCP Relay Agents ) that the message went through. The client sets this field to 0. one
xid A unique transaction identifier generated by the client at the beginning of the process for obtaining an address. four
secs The time in seconds since the beginning of the process of obtaining the address. May not be used (in this case it is set to 0). 2
flags Field for flags - special parameters of the DHCP protocol. 2
ciaddr IP address of the client. It is filled in only if the client already has its own IP address and is able to respond to requests from the ARP (this is possible if the client performs the procedure for updating the address after the lease expires). four
yiaddr The new client IP address offered by the server. four
siaddr IP address of the server. Returned in the DHCP offer (see below). four
giaddr The IP address of the relay agent, if one was involved in the delivery of the DHCP message to the server. four
chaddr The hardware address (usually the MAC address) of the client. sixteen
sname The optional server name as a null-terminated string. 64
file Optional file name on the server used by diskless workstations for remote boot. Like sname , is represented as a null-terminated string. 128
options DHCP options field. Various advanced configuration options are listed here. At the beginning of this field, four special bytes are specified with the values ​​99, 130, 83, 99 (“magic numbers”), allowing the server to determine the presence of this field. The field has a variable length, but the DHCP client must be ready to accept a DHCP message of 576 bytes in length (in this message, the options field is 340 bytes long). variable

An example of the process of obtaining the address (the algorithm of the DHCP)

Consider an example of the process of obtaining an IP address by a client from a DHCP server. Suppose the client does not yet have its own IP-address, but he knows his previous address - 192.168.1.100. The process consists of four stages.

DHCP discovery

Initially, the client performs a broadcast request across the entire physical network in order to discover available DHCP servers. It sends a message like DHCPDISCOVER , while 0.0.0.0 is specified as the source IP address (since the computer does not have its own IP address yet), and the destination address is the broadcast address 255.255.255.255.

The client fills several message fields with initial values:

  • The xid field contains a unique transaction identifier , which allows you to distinguish this process of obtaining an IP address from others proceeding at the same time.
  • The chaddr field contains the client’s hardware address (MAC address).
  • The options field indicates the last IP address known to the client. In this example, this is 192.168.1.100. This is optional and can be ignored by the server.

The DHCPDISCOVER message can be propagated outside the local physical network with the help of specially configured DHCP relay agents that redirect clients' DHCP messages to servers on other subnets.

Not always the process of obtaining an IP address begins with DHCPDISCOVER . If the client has previously received an IP address and its lease has not yet passed - the client can skip the DHCPDISCOVER stage, starting with a DHCPREQUEST request sent with the server identifier that issued the address last time. If there is no response from the DHCP server that issued the settings last time, the client sends a DHCPDISCOVER . Thus, the client begins the process of obtaining from the beginning, already accessing all DHCP servers in the network segment.

DHCP offer

After receiving a message from the client, the server determines the required configuration of the client in accordance with the settings specified by the network administrator. In this case, the DHCP server agrees with the requested client address 192.168.1.100. The server sends it a response ( DHCPOFFER ) in which it offers the configuration. The IP address offered to the client is indicated in the yiaddr field. Other parameters (such as addresses of routers and DNS servers) are indicated as options in the corresponding field.

This message is sent by the DHCP server to the host that sent the DHCPDISCOVER to its MAC. In certain circumstances, the message can be distributed as a broadcast. A client may receive several different DHCP offers from different servers; of them, he must choose the one that “suits” him.

DHCP request

By selecting one of the configurations suggested by the DHCP servers, the client sends a DHCP request ( DHCPREQUEST ). It is broadcast; at the same time, a special option is added to the options specified by the client in the DHCPDISCOVER message - server ID — indicating the address of the DHCP server selected by the client (in this case, 192.168.1.1).

DHCP acknowledgment

Finally, the server acknowledges the request and sends this acknowledgment ( DHCPACK ) to the client. After that, the client must configure its network interface using the options provided.

Kind of posts

Below are the values ​​of each field for each of the DHCP messages sent during the process.

DHCP discovery
DHCPDISCOVER
UDP Src = 0.0.0.0 Dest = 255.255.255.255
OP Htype Hlen HOPS
0x01 0x01 0x06 0x00
XID
0x3903F326
SECS Flags
0x0000 0x0000
CIADDR
0xC0A80164
YIADDR
0x00000000
SIADDR
0x00000000
GIADDR
0x00000000
CHADDR
0x0000001d6057ed80
SNAME
(empty field)
FILE
(empty field)
OPTIONS
DHCP Option 53: DHCP Discovery
DHCP option 50: request for address 192.168.1.100
DHCP offer
DHCPOFFER
UDP Src = 192.168.1.1 Dest = 255.255.255.255
OP Htype Hlen HOPS
0x02 0x01 0x06 0x00
XID
0x3903F326
SECS Flags
0x0000 0x0000
CIADDR
0x00000000
YIADDR
0xC0A80164
SIADDR
0xC0A80101
GIADDR
0x00000000
CHADDR
0x0000001d6057ed80
SNAME
(empty field)
FILE
(empty field)
OPTIONS
DHCP option 53: DHCP offer
DHCP option 1: subnet mask255.255.255.0
DHCP option 3: router 192.168.1.1
DHCP option 51: IP address lease term - 1 day
DHCP option 54: DHCP server 192.168.1.1
DHCP request
DHCPREQUEST
UDP Src = 0.0.0.0 Dest = 255.255.255.255
OP Htype Hlen HOPS
0x01 0x01 0x06 0x00
XID
0x3903F326
SECS Flags
0x0000 0x0000
CIADDR
0xC0A80164
YIADDR
0x00000000
SIADDR
0x00000000
GIADDR
0x00000000
CHADDR
0x0000001d6057ed80
SNAME
(empty field)
FILE
(empty field)
OPTIONS
DHCP option 53: DHCP request
DHCP option 50: request for address 192.168.1.100
DHCP option 54: DHCP server 192.168.1.1
DHCP acknowledgment
DHCPACK
UDP Src = 192.168.1.1 Dest = 255.255.255.255
OP Htype Hlen HOPS
0x02 0x01 0x06 0x00
XID
0x3903F326
SECS Flags
0x0000 0x0000
CIADDR
0x00000000
YIADDR
0xC0A80164
SIADDR
0x00000000
GIADDR
0x00000000
CHADDR
0x0000001d6057ed80
SNAME
(empty field)
FILE
(empty field)
OPTIONS
DHCP option 53: DHCP confirmation
DHCP option 1: subnet mask255.255.255.0
DHCP option 3: router 192.168.1.1
DHCP option 51: IP address lease term - 1 day
DHCP option 54: DHCP server 192.168.1.1

Other DHCP messages

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

Отказ DHCP

Если после получения подтверждения (DHCPACK) от сервера клиент обнаруживает, что указанный сервером адрес уже используется в сети, он рассылает широковещательное сообщение отказа DHCP ( DHCPDECLINE ), после чего процедура получения IP-адреса повторяется. Использование IP-адреса другим клиентом можно обнаружить, выполнив запрос ARP.

Сообщение отмены DHCP ( DHCPNAK ). При получении такого сообщения соответствующий клиент должен повторить процедуру получения адреса.

Освобождение DHCP

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

Информация DHCP

Сообщение информации DHCP ( DHCPINFORM ) предназначено для определения дополнительных параметров TCP/IP (например, адреса маршрутизаторапо умолчанию, DNS-серверов и т. п.) теми клиентами, которым не нужен динамический IP-адрес (то есть адрес которых настроен вручную). Серверы отвечают на такой запрос сообщением подтверждения (DHCPACK) без выделения IP-адреса.

Implementations

Компания Microsoft впервые включила сервер DHCP в поставку серверной версии Windows NT 3.5, выпущенной в 1994 году. Начиная с Windows 2000 Server реализация DHCP-сервера от Microsoft позволяет динамически обновлять записи DNS, что используется в Active Directory.

Internet Systems Consortium выпустил первую версию ISC DHCP Server (для Unix-подобных систем) 6 декабря 1997 года. 22 июня 1999 года вышла версия 2.0, более точно соответствующая стандарту.

Компания Cisco включила сервер DHCP в Cisco IOS 12.0 в феврале 1999 года. Sun добавила DHCP-сервер в Solaris 8 в июле 2001 года.

В настоящее время существуют реализации сервера DHCP для ОС Windows в виде отдельных программ, в том числе открытых [2] , позволяющих выполнять роль сервера DHCP компьютерам под управлением не серверных версий данной ОС.

Недостатки DHCP

Освобождая сетевых администраторов от множества рутинных операций, DHCP оставляет нерешенными ряд проблем, которые рано или поздно могут возникнуть в реальной сетевой среде.

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

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

* * *

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

Тем не менее, как частенько бывает в сетевой индустрии, механизмы DHCP уже реализованы в продуктах ряда производителей. К счастью, любые изменения в алгоритмах его работы легко учесть на программном уровне, так что, приобретая серверное или клиентское программное обеспечение определенной компании, можно не опасаться заточения в неприступную крепость патентованных решений. Скорее, следует обратить внимание на то, насколько удачно конкретная реализация DHCP вписывается в имеющуюся вычислительную среду и взаимодействует с другими сетевыми службами, в частности с DNS. Публикуемые в этом номере результаты сравнительных испытаний DNS- и DHCP-серверов (см. статью <Игра в имена>) способны стать неплохим подспорьем для пользователя.

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

Распределение IP-адресов: возможны варианты

BOOTP, DRARP, TFTP, ICMP, NIP - вероятно, это еще не полный перечень протоколов, в той или иной мере претендующих на решение задачи управления IP-адресами и конфигурацией в сетевой среде. Не исключено, что после стандартизации DHCP довольно быстро вытеснит их со сцены, однако на сегодняшний день многие из названных протоколов нередко упоминаются в литературе и используются в готовых продуктах.

Like DHCP, the Bootstrap Protocol (BOOTP) today also has the status of a preliminary standard and is recommended for use by the IETF consortium. It should be considered the immediate predecessor of DHCP. The additions that appeared in 1993 expanded the list of configuration parameters covered by the BOOTP protocol. Moreover, by now even a modification of BOOTP has been proposed that supports dynamic assignment of IP addresses.

Протокол Reverse Address Resolution Protocol (RARP), впервые описанный в июне 1984 г. (RFC 903), используется компанией Sun Microsystems и рядом других производителей, в частности, для запуска бездисковых рабочих станций. Основной принцип его работы сводится к тому, что клиент должен самостоятельно отыскать свой IP-адрес, а не принять адрес, выделенный сервером. Сравнительно недавно появился динамический вариант этого протокола (Dynamic RARP, DRARP), реализующий алгоритм автоматического присвоения IP-адресов. Стоит отметить, что изначальный вариант RARP не поддерживает передачу клиенту каких-либо параметров конфигурации (кроме IP-адреса), в том числе применяемых при маршрутизации. В результате один сервер RARP способен обслуживать только одну локальную сеть.

A simplified version of FTP — the Trivial File Transfer Protocol (TFTP) protocol — was released about 20 years ago; its second version is described in RFC 783. In fact, TFTP provides a transport mechanism for transferring a client system’s boot image from a server.

The Internet Control Message Protocol (ICMP) today can also be attributed to the generation of veterans of the World Wide Web. It allows computers to be informed about the presence of additional routers in the network (there is a special mechanism for detecting these devices), provides special types of messages for transmitting the subnet mask and other official information.

Finally, the Network Information Protocol (NIP) was developed in the late 1980s. employees at MIT as a distributed mechanism for dynamically assigning IP addresses on Ethernet networks.

Note also the specifications of RFC 1122 and 1123, which are used by a number of protocols (including DHCP). They contain requirements for the procedure for changing the configuration of computers on a network and, in addition, suggest a scenario for the initial configuration of diskless stations.


DHCP and VLAN: there are more differences than similarities

From time to time, one can come across a statement that DHCP and virtual private network technology (VLAN) are aimed at solving the same problem: they must ensure the free movement of clients in a network environment. In fact, the above abbreviations conceal two completely different concepts, and the approach based on virtual drugs is much more revolutionary.

The DHCP server and relay agents enable you to configure the computer’s configuration settings so that, after being removed from one subnet and connected to another, it immediately becomes a full member of the new subnet (since the configuration of the moved machine changes automatically). If, in addition, support is provided for a dynamic domain name server (Dynamic DNS), the computer acquires its former name.

The network equipment endowed with the dynamic formation of virtual LANs makes it possible to determine the network configuration in such a way that no matter which port of the hub or switch the client station is connected to, it will receive the same IP address and name and be included in the previously described virtual network. local network. The distribution of MAC addresses over virtual LANs can be set by the network configuration itself. Another option assumes that IP addresses are recognized by the packets that come from the client stations.

So, the differences between the DHCP protocol and the VLAN technology can be summarized as follows:

  • DHCP changes the configuration of the roaming computer, whereas on a VLAN-enabled network, the network port to which the computer is connected changes;
  • Dynamic reconfiguration by means of DHCP requires a DHCP server, a relay agent in each router, and TCP / IP client software support for this protocol. In the case of the use of VLAN technology, the same VLAN scheme must be supported by all hubs (switches) of the network, which opens up a wide scope for proprietary implementations;
  • DHCP allows you to configure a new client station, but VLAN tools do not;
  • DHCP protocol serves primarily to provide the most dynamic configuration of a network divided into subnets according to a territorial basis. The main purpose of VLAN technology is to unite users not according to geographical, but according to some other, for example, functional, principle (according to the nature of their activity or role in the company's business).

As is clear from this brief comparison, the simultaneous use of DHCP on a network (or its prototype BOOTP) and VLAN facilities can lead to serious conflicts. So, if the grouping of clients into virtual local networks is carried out on the basis of source IP addresses (i.e., a predefined configuration), then receiving configuration data over the network from a DHCP server is excluded.

3. Client-server protocol. DHCP algorithm

DHCP uses the BOOTP message format defined in RFC-951 and presented in Table 1 and Figure 2. 1. The 'op' field of each DHCP message sent by the client to the server contains a BOOTREQUEST. In the 'op' field of the DHCP message sent by the server to the client, BOOTREPLY is entered.

The first 4 octets of the option field of the DHCP message contain (decimal) codes 99, 130, 83, and 99, respectively (these are the same (magic cookie) codes as defined in RFC-1497 [17]). The rest of the 'options' field consists of a list of flagged parameters, called "options". All vendor extensions listed in RFC-1497 are also DHCP options. RFC-1533 provides a full set of options defined for use with DHCP.

Several options are already defined. One of them is the option "DHCP message type", which should be included in all DHCP messages. This option specifies the type of DHCP message. Additional options may be allowed, required or not allowed depending on the type of DHCP message.

For the purposes of this document, DHCP messages that contain the DHCP Message Type option will be interpreted according to the message type; for example, a DHCP message with an option type equal to 1 will be interpreted as a "DHCPDISCOVER" message.

3.1. Client and server interaction when allocating a network address

Below is a protocol exchange between the client and the server of the DHCP messages described in Table 2. The timing diagram in Figure 2. 3 shows a typical client / server interaction scheme. If the client already knows his address, some steps may be omitted; such simplified interaction is described in section 3.2.

one. The client broadcasts the DHCPDISCOVER message over the local physical subnet. The DHCPDISCOVER message may include options that suggest values ​​for the network address and the duration of its use. The BOOTP transport agent can send a message to DHCP servers that are located outside this physical subnet.
2 Each server can respond with a DHCPOFFER message that contains the network address in the 'yiaddr' field (and other configuration parameters in the DHCP options). Servers should not reserve the proposed network address, although the protocol will work more efficiently if the server avoids assigning the proposed network address to another client. When allocating a new address, the servers should check that the proposed network address is not used elsewhere; for example, the server can test the proposed address using an ICMP echo request. Servers must be implemented so that network administrators can select the desired tests for newly allocated addresses. The server sends a DHCPOFFER message to the client using, if necessary, BOOTP vehicles.

Table 2: DHCP Messages

Message Using
DHCPDISCOVER The client broadcasts a message to discover an available server.
DHCPOFFER It is sent by the server to the client in response to the DHCPDISCOVER message and contains a suggestion for configuration parameters.
DHCPREQUEST A client message to the server or (a) requesting parameters from one server and implicitly rejecting offers from other servers, (b) confirming the correctness of a previously assigned address after, for example, rebooting the system, or (c) requesting an extension of the lifetime of a specific network address.
DHCPACK It is sent by the server to the client and contains the configuration parameters, including the assigned network address.
DHCPNAK Sent by the server to the client, indicating that the network address is not correct (for example, the client has moved to a new subnet), or the client has expired
DHCPDECLINE The client and server found that the network address is already in use.
DHCPRELEASE It is sent by the client to the server in order to refuse the network address and cancels the remaining time of the address.
DHCPINFORM Sent by client to server for local configuration parameters; The client already has a network address received from outside.

DHCP - Dynamic Host Configuration Protocol - Operational Algorithm

Fig. 3. Temporary messaging diagram between the DHCP client and the server during the assignment of a new network address

3 A client receives one or more DHCPOFFER messages from one or more servers. The client may prefer to wait for several responses. The client selects one server to which it will send a request for configuration parameters, according to the proposal contained in the DHCPOFFER message. The client broadcasts a DHCPREQUEST message, which must contain the 'server identifier' option to indicate which server is selected by it, and which may include other options specifying the desired configuration values. The 'requested IP address' option in the DHCPOFFER server message should contain the value 'yiaddr'. The DHCPREQUEST message is broadcast by DHCP / BOOTP transport agents. To ensure that any BOOTP transport agent sends a DHCPREQUEST message to the same set of DHCP servers that received the original DHCPDISCOVER message, the DHCPREQUEST message should use the same value of the 'secs' field of the DHCP message header and should be sent over the same broadcast IP address as the original DHCPDISCOVER message. The client implements a timeout and resends the DHCPDISCOVER message if it does not receive a DHCPOFFER message.
four. Servers receive a DHCPREQUEST broadcast message from the client. Servers not selected by the DHCPREQUEST message use the message as notifications that the client has rejected the server offer. The server selected by the DHCPREQUEST message writes the client's configuration set to persistent memory and responds with a DHCPACK message containing the configuration parameters for the client that sent the request. The combination of 'client identifier' or 'chaddr' and the assigned network address is a unique identifier for the duration of the client's address and is used by the client and server to identify this time in any DHCP message. Any configuration parameters in the DHCPACK message should not conflict with the parameters from the DHCPOFFER message to which the client responds. The server should not check the proposed network address. In the 'yiaddr' field of the DHCPACK messages, the selected network address is recorded.

If the selected server cannot adequately respond to a DHCPREQUEST message (for example, the requested network address has already been allocated), the server should respond by sending a DHCPNAK message.

The server should mark the address offered to the client in the DHCPOFFER message as available if the server has not received any DHCPREQUEST message from the client.

five. The client receives a DHCPACK message containing the configuration parameters. The client must perform a final check of the parameters (for example, run ARP for the allocated network address), and record the duration of the provision of the configuration parameters specified in the DHCPACK message. The client is finally configured. If the client detects that the address is already in use (for example, using ARP), it must send a DHCPDECLINE message to the server and rerun the configuration process. The client must wait at least 10 seconds before restarting the configuration procedure to avoid unnecessary network traffic. If the client receives a DHCPNAK message, the client restarts the configuration process.

The client implements a timeout and resends the DHCPREQUEST message if the client does not receive either DHCPACK or DHCPNAK messages. The client resends the DHCPREQUEST according to the re-forwarding algorithm described in section 4.1. The client must select an adequate number of retransmissions of the DHCPREQUEST message in order to ensure a sufficient likelihood of access to the server without forcing the client (and the user of this client) to wait too long; for example, a client, performing a re-forwarding as described in section 4.1, may re-send a DHCPREQUEST message four times, with a total delay of 60 seconds, before re-starting the initialization procedure. If the client does not receive either a DHCPACK or a DHCPNAK message after applying the re-forwarding algorithm, the client returns to its original state and restarts the initialization process. The client must notify the user that the initialization process has failed and a retry is made.

6 The client may decide to cancel the lease of the network address by sending a DHCPRELEASE message to the server. The client identifies the set of parameters that it refuses with its identifier, or 'chaddr' and the network address in the DHCPRELEASE message. If a client used a client identifier when it received a set of configuration parameters, the client must use the same client identifier in the DHCPRELEASE message.

3.2. Client and server interaction when reusing previously allocated network addresses

If the client remembers and wants to use the previously allocated network address, it may omit some of the steps described in the previous section. The timing diagram in fig. Figure 4 shows the typical client and server interaction in the case of reusing the old network address.

one. The client broadcasts a DHCPREQUEST message over the local subnet. The message includes the client’s network address in the 'requested IP address' option. Once the client has not received his network address, he does not have to fill in the 'ciaddr' field. BOOTP transport agents send a message to DHCP servers outside this subnet. If the client uses the 'client identifier' to obtain its address, the client must use the same 'client identifier' in the DHCPREQUEST message.
2 Servers that know the client’s configuration parameters respond with a DHCPACK message. Servers should not check if the client’s network address is already being used; The client may respond by sending an ICMP echo request.

DHCP - Dynamic Host Configuration Protocol - Operational Algorithm

Fig. .four. Timing messaging diagram between a DHCP client and server when reassigning a previously used network address

If the client request is not correct (for example, the client has moved to another subnet), the servers should respond by sending a DHCPNAK message to the client. Servers should not respond if their information is not absolutely reliable. For example, a server that identifies a request for a parameter set that belongs to another server and has an expired validity, the server should not respond with a DHCPNAK message, unless the servers explicitly use a coherent mechanism.

If the 'giaddr' in the DHCPREQUEST message is 0x0, the client is on the same subnet as the server. The server must broadcast a DHCPNAK message at 0xffffffff, because the client may not have the correct network address or network mask, and the client may not respond to an ARP request. Otherwise, the server should send a DHCPNAK message to the IP address of the BOOTP transport agent recorded in 'giaddr'. The transport agent, in turn, forwards the message directly to the client’s hardware address, so DHCPNAK will be delivered even if the client has moved to another network.

3 The client receives a DHCPACK message containing the configuration parameters. The client performs a final parameter check (as in Section 3.1), and marks the configuration validity time specified in the DHCPACK message. The action time value is implicitly specified by the 'client identifier' or 'chaddr' and the network address. From this point on, the client is considered configured.

If the client detects that the IP address in the DHCPACK message has already been used, the client should send a DHCPDECLINE message to the server and rerun the configuration process by sending a request to the new network address. This action corresponds to the client transition to the INIT state in the DHCP state diagram, which is described in section 4.4.

If the client receives a DHCPNAK message, it cannot reuse its memorized network address. It must instead request a new address by re-running the configuration process. This action corresponds to the client transitioning to the INIT state in the DHCP state diagram.

The client times out and resends the DHCPREQUEST message. If the client does not receive either the DHCPACK message or the DHCPNAK, the client re-sends the DHCPREQUEST message according to the algorithm in section 4.1. The client must select an adequate number of retransmissions of the DHCPREQUEST message in order to ensure a sufficient likelihood of access to the server without forcing the client (and the user of this client) to wait too long. For example, a client, performing a re-forwarding as described in section 4.1, can retransmit the DHCPREQUEST message four times with a total delay of 60 seconds before re-starting the initialization procedure. If the client has not received any DHCPACK or DHCPNAK messages after the second transfer, it can decide to use the previously assigned network address and configuration parameters until their expiration date. This corresponds to the transition to the BOUND state in the client state diagram shown in Figure 2. five.

four. The client may decide to refuse the network address by sending a DHCPRELEASE message to the server. The client identifies the set of parameters that it refuses, using the 'client identifier', or 'chaddr' and the network address in the DHCPRELEASE message.

Заметим, что в случае, когда клиент сохраняет свой сетевой адрес локально, при корректном прерывании сессии (shutdown) он не должен отказываться от конфигурационного набора. Только в случае, когда клиенту нужно отказаться от конфигурационного набора, например, клиент намеривается перейти в другую субсеть, он будет должен послать сообщение DHCPRELEASE.

3.3. Интерпретация и представление значений времени

Клиент получает сетевой адрес на определенный период времени (который может быть бесконечным). В данном протоколе время измеряется в секундах. Значение времени 0xffffffff зарезервировано для обозначения бесконечности.

Так как клиент и сервер могут не иметь синхронизованных часов, значения времени в DHCP-сообщения являются относительными, и должны интерпретироваться с учетом показаний локальных часов клиента. Время измеряется в секундах и представляется в виде 32-битных кодов без знака. Это позволяет описывать относительные интервалы времени от 0 до примерно 100 лет, что вполне приемлемо для целей протокола DHCP.

Алгоритм интерпретации времени действия конфигурационного набора, представленный в предыдущем параграфе, предполагает, что часы клиента и сервера стабильны относительно друг друга. Если имеется относительный дрейф этих часов, сервер может считать время действия конфигурационного набора исчерпанным, а клиент - нет. Чтобы компенсировать такого рода эффект, сервер может послать клиенту значение времени действия короче того, которое он записывает в свою базу данных.

3.4. Получение параметров при внешне заданных адресах

Если клиент получил сетевой адрес каким-то другим образом (например, при ручной конфигурации), он может использовать запрос-сообщение DHCPINFORM, чтобы получить другие локальные конфигурационные параметры. Серверы, получив сообщение DHCPINFORM, формируют сообщение DHCPACK с любыми конфигурационными параметрами, приемлемыми для клиента. При этом сетевой адрес не присваивается, не проверяется существующий набор параметров, не заполняется 'yiaddr' и не задаются параметры времени действия конфигурационного набора. Серверы должны послать ответ DHCPACK по уникастному адресу, заданному в поле 'ciaddr' сообщения DHCPINFORM.

Сервер в целях совместимости должен проверить сетевой адрес в сообщении DHCPINFORM, но не должен проверять существующее значение времени действия конфигурационного набора. Сервер формирует сообщение DHCPACK, содержащее конфигурационные параметры для клиента, приславшего запрос, и посылает сообщение DHCPACK непосредственно клиенту.

3.5. Параметры клиента в DHCP

Не все клиенты требуют инициализации всех параметров, перечисленных в приложении A. Используются два способа сокращения числа параметров, пересылаемых от сервера клиенту. 1. Большинство параметров имеет значения по умолчанию, определенные в Host Requirements RFC; если клиент не получил параметров от сервера, которые переписывают значения по умолчанию, клиент использует эти значения. 2. В своем исходном сообщении DHCPDISCOVER или DHCPREQUEST, клиент может предоставить серверу список специфических параметров, которые ему нужны. Если клиент включает список параметров в сообщение DHCPDISCOVER, он должен включать этот список в любое последующее сообщение DHCPREQUEST.

Клиент должен включить опцию 'maximum DHCP message size', чтобы позволить серверу знать, максимальный размер его DHCP-сообщений. Параметры, присланные в ответ клиенту, могут иметь размер больший, чем выделено для опций в сообщении DHCP. В этом случае, два дополнительных опционных флага (которые должны присутствовать в поле 'опции' сообщения) индицируют, что для опций должны использоваться поля 'file' и 'sname'.

Клиент может проинформировать сервер о том, в каких конфигурационных параметрах заинтересован клиент, включив опцию 'parameter request list'.

Кроме того, клиент может предложить значения для сетевого адреса и времени его действия в сообщении DHCPDISCOVER. Клиент может включить опцию 'requested IP-адрес', чтобы предложить конкретное значение IP-адреса, которое он хотел бы получить, и может включить опцию 'IP-адрес lease time', чтобы предложить предпочтительное значение времени действия конфигурационного набора. Другие опции, представляющие рекомендации по конфигурационным параметрам, допустимы в сообщении DHCPDISCOVER или DHCPREQUEST. Однако дополнительные опции могут игнорироваться серверами, и разные серверы могут прислать различные отклики на одни и те же опции. Опция 'requested IP-адрес' должна заноситься только в сообщение DHCPREQUEST, когда клиент проверяет конфигурационные параметры, полученные ранее. Клиент заполняет поле 'ciaddr', только когда он имеет корректный IP-адрес в состояниях BOUND, RENEWING или REBINDING.

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

3.6. Применение DHCP для клиентов с несколькими интерфейсами

Клиент с несколькими сетевыми интерфейсами должен использовать DHCP для получения конфигурационных параметров через каждый из интерфейсов независимо.

3.7. Когда клиентам следует использовать DHCP?

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

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


Источники информации

Спецификация протокола DHCP описана в RFC 2131 и ряде вспомогательных документов, перечень и тексты которых можно найти в Internet по адресу http://www.ietf.org/html.charters/dhc-charter.html . Там же имеется обширный список предварительных спецификаций (Internet Drafts), регламентирующих различные аспекты работы данного протокола.

Документы RFC содержатся и на ряде других Web-серверов, например http://info.internet.isi.edu/ls/in-notes/rfc/ ; http://www.cis.ohio-state.edu/hypertext/information/rfc.html ; http://www.pmg.lcs.mit.edu/rfc.html .

Подборка документов Internet Drafts по протоколу DHCP размещена на серверах ftp.bucknell.edu/pub/dhcp/ и http://www.bucknell.edu/~droms/dhcp/ .

Информация по протоколу DHCP, что называется, из первых рук, а также многие вспомогательные материалы доступны на сервере соответствующей рабочей группы: http://www.dhcp.org .


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Computer networks

Terms: Computer networks