Icmp это протокол устранения ошибок

From Wikipedia, the free encyclopedia

This article is about the support protocol for IPv4 (ICMPv4). For ICMPv6, see ICMPv6.

Internet Control Message Protocol

Communication protocol
ICMP header - General-en.svg

A general header for ICMPv4

Purpose Auxiliary protocol for IPv4[1]
Developer(s) DARPA
Introduction 1981
OSI layer Network layer
RFC(s) RFC 792

The Internet Control Message Protocol (ICMP) is a supporting protocol in the Internet protocol suite. It is used by network devices, including routers, to send error messages and operational information indicating success or failure when communicating with another IP address, for example, an error is indicated when a requested service is not available or that a host or router could not be reached.[2] ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems, nor is it regularly employed by end-user network applications (with the exception of some diagnostic tools like ping and traceroute).

ICMP for IPv4 is defined in RFC 792. A separate ICMPv6, defined by RFC 4443, is used with IPv6.

Technical details[edit]

ICMP is part of the Internet protocol suite as defined in RFC 792. ICMP messages are typically used for diagnostic or control purposes or generated in response to errors in IP operations (as specified in RFC 1122). ICMP errors are directed to the source IP address of the originating packet.[2]

For example, every device (such as an intermediate router) forwarding an IP datagram first decrements the time to live (TTL) field in the IP header by one. If the resulting TTL is 0, the packet is discarded and an ICMP time exceeded in transit message is sent to the datagram’s source address.

Many commonly used network utilities are based on ICMP messages. The traceroute command can be implemented by transmitting IP datagrams with specially set IP TTL header fields, and looking for ICMP time exceeded in transit and Destination unreachable messages generated in response. The related ping utility is implemented using the ICMP echo request and echo reply messages.

ICMP uses the basic support of IP as if it were a higher-level protocol, however, ICMP is actually an integral part of IP. Although ICMP messages are contained within standard IP packets, ICMP messages are usually processed as a special case, distinguished from normal IP processing. In many cases, it is necessary to inspect the contents of the ICMP message and deliver the appropriate error message to the application responsible for transmitting the IP packet that prompted the ICMP message to be sent.

ICMP is a network-layer protocol, this makes it layer 3 protocol by the 7 layer OSI model. Based on the 4 layer TCP/IP model, ICMP is an internet-layer protocol, which makes it layer 2 protocol (internet standard RFC 1122 TCP/IP model with 4 layers) or layer 3 protocol based on modern 5 layer TCP/IP protocol definitions (by Kozierok, Comer, Tanenbaum, Forouzan, Kurose, Stallings).[citation needed] Forouzan and Kurose use network-layer instead of internet-layer in their TCP/IP model definition. These differences between models often lead to pointless and endless debates.[according to whom?]

There is no TCP or UDP port number associated with ICMP packets as these numbers are associated with the transport layer above.[3]

Datagram structure[edit]

The ICMP packet is encapsulated in an IPv4 packet.[2] The packet consists of header and data sections.

[edit]

The ICMP header starts after the IPv4 header and is identified by IP protocol number ‘1’.[4] All ICMP packets have an 8-byte header and variable-sized data section. The first 4 bytes of the header have fixed format, while the last 4 bytes depend on the type/code of that ICMP packet.[2]

ICMP header format

Offsets Octet 0 1 2 3
Octet Bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 0 Type Code Checksum
4 32 Rest of header
Type
ICMP type, see § Control messages.
Code
ICMP subtype, see § Control messages.
Checksum
Internet checksum (RFC 1071) for error checking, calculated from the ICMP header and data with value 0 substituted for this field.
Rest of header
Four-byte field, contents vary based on the ICMP type and code.

Data[edit]

ICMP error messages contain a data section that includes a copy of the entire IPv4 header, plus at least the first eight bytes of data from the IPv4 packet that caused the error message. The length of ICMP error messages should not exceed 576 bytes.[5] This data is used by the host to match the message to the appropriate process. If a higher level protocol uses port numbers, they are assumed to be in the first eight bytes of the original datagram’s data.[6]

The variable size of the ICMP packet data section has been exploited. In the «Ping of death», large or fragmented ICMP packets are used for denial-of-service attacks. ICMP data can also be used to create covert channels for communication. These channels are known as ICMP tunnels.

Control messages[edit]

Control messages are identified by the value in the type field. The code field gives additional context information for the message. Some control messages have been deprecated since the protocol was first introduced.

Notable control messages[7][8]

Type Code Status Description
0 – Echo Reply[6]: 14  0 Echo reply (used to ping)
1 and 2 unassigned Reserved
3 – Destination Unreachable[6]: 4  0 Destination network unreachable
1 Destination host unreachable
2 Destination protocol unreachable
3 Destination port unreachable
4 Fragmentation required, and DF flag set
5 Source route failed
6 Destination network unknown
7 Destination host unknown
8 Source host isolated
9 Network administratively prohibited
10 Host administratively prohibited
11 Network unreachable for ToS
12 Host unreachable for ToS
13 Communication administratively prohibited
14 Host Precedence Violation
15 Precedence cutoff in effect
4 – Source Quench 0 deprecated Source quench (congestion control)
5 – Redirect Message 0 Redirect Datagram for the Network
1 Redirect Datagram for the Host
2 Redirect Datagram for the ToS & network
3 Redirect Datagram for the ToS & host
6 deprecated Alternate Host Address
7 unassigned Reserved
8 – Echo Request 0 Echo request (used to ping)
9 – Router Advertisement 0 Router Advertisement
10 – Router Solicitation 0 Router discovery/selection/solicitation
11 – Time Exceeded[6]: 6  0 TTL expired in transit
1 Fragment reassembly time exceeded
12 – Parameter Problem: Bad IP header 0 Pointer indicates the error
1 Missing a required option
2 Bad length
13 – Timestamp 0 Timestamp
14 – Timestamp Reply 0 Timestamp reply
15 – Information Request 0 deprecated Information Request
16 – Information Reply 0 deprecated Information Reply
17 – Address Mask Request 0 deprecated Address Mask Request
18 – Address Mask Reply 0 deprecated Address Mask Reply
19 reserved Reserved for security
20 through 29 reserved Reserved for robustness experiment
30 – Traceroute 0 deprecated Information Request
31 deprecated Datagram Conversion Error
32 deprecated Mobile Host Redirect
33 deprecated Where-Are-You (originally meant for IPv6)
34 deprecated Here-I-Am (originally meant for IPv6)
35 deprecated Mobile Registration Request
36 deprecated Mobile Registration Reply
37 deprecated Domain Name Request
38 deprecated Domain Name Reply
39 deprecated SKIP Algorithm Discovery Protocol, Simple Key-Management for Internet Protocol
40 Photuris, Security failures
41 Experimental ICMP for experimental mobility protocols such as Seamoby [RFC4065]
42 – Extended Echo Request[9] 0 Request Extended Echo (XPing — see Extended Ping (Xping))
43 – Extended Echo Reply[9] 0 No Error
1 Malformed Query
2 No Such Interface
3 No Such Table Entry
4 Multiple Interfaces Satisfy Query
44 through 252 unassigned Reserved
253 Experimental RFC3692-style Experiment 1 (RFC 4727)
254 Experimental RFC3692-style Experiment 2 (RFC 4727)
255 reserved Reserved

Source quench[edit]

Source Quench requests that the sender decrease the rate of messages sent to a router or host. This message may be generated if a router or host does not have sufficient buffer space to process the request, or may occur if the router or host buffer is approaching its limit.

Data is sent at a very high speed from a host or from several hosts at the same time to a particular router on a network. Although a router has buffering capabilities, the buffering is limited to within a specified range. The router cannot queue any more data than the capacity of the limited buffering space. Thus if the queue gets filled up, incoming data is discarded until the queue is no longer full. But as no acknowledgement mechanism is present in the network layer, the client does not know whether the data has reached the destination successfully. Hence some remedial measures should be taken by the network layer to avoid these kind of situations. These measures are referred to as source quench. In a source quench mechanism, the router sees that the incoming data rate is much faster than the outgoing data rate, and sends an ICMP message to the clients, informing them that they should slow down their data transfer speeds or wait for a certain amount of time before attempting to send more data. When a client receives this message, it will automatically slow down the outgoing data rate or wait for a sufficient amount of time, which enables the router to empty the queue. Thus the source quench ICMP message acts as flow control in the network layer.

Since research suggested that «ICMP Source Quench [was] an ineffective (and unfair) antidote for congestion»,[10] routers’ creation of source quench messages was deprecated in 1995 by RFC 1812. Furthermore, forwarding of and any kind of reaction to (flow control actions) source quench messages was deprecated from 2012 by RFC 6633.

Source quench message[6]: 9 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 4 Code = 0 Checksum
unused
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 4
Code must be set to 0
IP header and additional data is used by the sender to match the reply with the associated request

Redirect[edit]

An example of how an ICMPv4 redirect message works

Redirect requests data packets be sent on an alternative route. ICMP Redirect is a mechanism for routers to convey routing information to hosts. The message informs a host to update its routing information (to send packets on an alternative route). If a host tries to send data through a router (R1) and R1 sends the data on another router (R2) and a direct path from the host to R2 is available (that is, the host and R2 are on the same subnetwork), then R1 will send a redirect message to inform the host that the best route for the destination is via R2. The host should then change its route information and send packets for that destination directly to R2. The router will still send the original datagram to the intended destination.[11] However, if the datagram contains routing information, this message will not be sent even if a better route is available. RFC 1122 states that redirects should only be sent by gateways and should not be sent by Internet hosts.

Redirect message[6]: 11 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 5 Code Checksum
IP address
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 5.
Code specifies the reason for the redirection, and may be one of the following:
Code Description
0 Redirect for Network
1 Redirect for Host
2 Redirect for Type of Service and Network
3 Redirect for Type of Service and Host
IP address is the 32-bit address of the gateway to which the redirection should be sent.
IP header and additional data is included to allow the host to match the reply with the request that caused the redirection reply.

Time exceeded[edit]

Time Exceeded is generated by a gateway to inform the source of a discarded datagram due to the time to live field reaching zero. A time exceeded message may also be sent by a host if it fails to reassemble a fragmented datagram within its time limit.

Time exceeded messages are used by the traceroute utility to identify gateways on the path between two hosts.

Time exceeded message[6]: 5 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 11 Code Checksum
unused
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 11
Code specifies the reason for the time exceeded message, include the following:
Code Description
0 Time-to-live exceeded in transit.
1 Fragment reassembly time exceeded.
IP header and first 64 bits of the original payload are used by the source host to match the time exceeded message to the discarded datagram. For higher-level protocols such as UDP and TCP the 64-bit payload will include the source and destination ports of the discarded packet.

Timestamp[edit]

Timestamp is used for time synchronization. The originating timestamp is set to the time (in milliseconds since midnight) the sender last touched the packet. The receive and transmit timestamps are not used.

Timestamp message[6]: 15 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 13 Code = 0 Checksum
Identifier Sequence number
Originate timestamp
Receive timestamp
Transmit timestamp

Where:

Type must be set to 13
Code must be set to 0
Identifier and Sequence Number can be used by the client to match the timestamp reply with the timestamp request.
Originate timestamp is the number of milliseconds since midnight Universal Time (UT). If a UT reference is not available the most-significant bit can be set to indicate a non-standard time value.

Timestamp reply[edit]

Timestamp Reply replies to a Timestamp message. It consists of the originating timestamp sent by the sender of the Timestamp as well as a receive timestamp indicating when the Timestamp was received and a transmit timestamp indicating when the Timestamp reply was sent.

Timestamp reply message[6]: 15 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 14 Code = 0 Checksum
Identifier Sequence number
Originate timestamp
Receive timestamp
Transmit timestamp

Where:

Type must be set to 14
Code must be set to 0
Identifier and Sequence number can be used by the client to match the reply with the request that caused the reply.
Originate timestamp is the time the sender last touched the message before sending it.
Receive timestamp is the time the echoer first touched it on receipt.
Transmit timestamp is the time the echoer last touched the message on sending it.
All timestamps are in units of milliseconds since midnight UT. If the time is not available in milliseconds or cannot be provided with respect to midnight UT then any time can be inserted in a timestamp provided the high order bit of the timestamp is also set to indicate this non-standard value.

The use of Timestamp and Timestamp Reply messages to synchronize the clocks of Internet nodes has largely been replaced by the UDP-based Network Time Protocol and the Precision Time Protocol.[12]

Address mask request[edit]

Address mask request is normally sent by a host to a router in order to obtain an appropriate subnet mask.

Recipients should reply to this message with an Address mask reply message.

Address mask request

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 17 Code = 0 Checksum
Identifier Sequence number
Address mask

Where:

Type must be set to 17
Code must be set to 0
Address mask can be set to 0

ICMP Address Mask Request may be used as a part of reconnaissance attack to gather information on the target network, therefore ICMP Address Mask Reply is disabled by default on Cisco IOS.[13]

Address mask reply[edit]

Address mask reply is used to reply to an address mask request message with an appropriate subnet mask.

Address mask reply

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 18 Code = 0 Checksum
Identifier Sequence number
Address mask

Where:

Type must be set to 18
Code must be set to 0
Address mask should be set to the subnet mask

Destination unreachable[edit]

Destination unreachable is generated by the host or its inbound gateway[6] to inform the client that the destination is unreachable for some reason. Reasons for this message may include: the physical connection to the host does not exist (distance is infinite); the indicated protocol or port is not active; the data must be fragmented but the ‘don’t fragment’ flag is on. Unreachable TCP ports notably respond with TCP RST rather than a destination unreachable type 3 as might be expected. Destination unreachable is never reported for IP multicast transmissions.

Destination unreachable message[6]: 3 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 3 Code Checksum
unused Next-hop MTU
IP header and first 8 bytes of original datagram’s data

Where:

Type field (bits 0–7) must be set to 3
Code field (bits 8–15) is used to specify the type of error, and can be any of the following:
Code Description
0 Network unreachable error.
1 Host unreachable error.
2 Protocol unreachable error (the designated transport protocol is not supported).
3 Port unreachable error (the designated protocol is unable to inform the host of the incoming message).
4 The datagram is too big. Packet fragmentation is required but the ‘don’t fragment’ (DF) flag is on.
5 Source route failed error.
6 Destination network unknown error.
7 Destination host unknown error.
8 Source host isolated error.
9 The destination network is administratively prohibited.
10 The destination host is administratively prohibited.
11 The network is unreachable for Type Of Service.
12 The host is unreachable for Type Of Service.
13 Communication administratively prohibited (administrative filtering prevents packet from being forwarded).
14 Host precedence violation (indicates the requested precedence is not permitted for the combination of host or network and port).
15 Precedence cutoff in effect (precedence of datagram is below the level set by the network administrators).
Next-hop MTU field (bits 48–63) contains the MTU of the next-hop network if a code 4 error occurs.[14]
IP header and additional data is included to allow the client to match the reply with the request that caused the destination unreachable reply.

See also[edit]

  • ICMP tunnel
  • ICMP hole punching
  • ICMP Router Discovery Protocol
  • Pathping
  • Path MTU Discovery
  • Smurf attack

References[edit]

  1. ^ F. Baker (June 1995). Baker, F (ed.). Requirements for IP Version 4 Routers. p. 52. RFC 1812.
  2. ^ a b c d Forouzan, Behrouz A. (2007). Data Communications And Networking (Fourth ed.). Boston: McGraw-Hill. pp. 621–630. ISBN 978-0-07-296775-3.
  3. ^ «The OSI Model’s Seven Layers Defined and Functions Explained». Microsoft Support. Retrieved 2014-12-28.
  4. ^ «Protocol Numbers». Internet Assigned Numbers Authority. Retrieved 2011-06-23.
  5. ^ Requirements for IP Version 4 Routers. doi:10.17487/RFC1812. RFC 1812.
  6. ^ a b c d e f g h i j k Postel, J. (September 1981). Internet Control Message Protocol. IETF. doi:10.17487/RFC0792. RFC 792.
  7. ^ «IANA ICMP Parameters». Iana.org. 2012-09-21. Retrieved 2013-01-07.
  8. ^ Kurose, J.F; Ross, K.W. (2006). Computer Networking: A Top-Down Approach. World student series. Addison-Wesley. ISBN 9780321418494.
  9. ^ a b PROBE: A Utility for Probing Interfaces. doi:10.17487/RFC8335. RFC 8335.
  10. ^ RFC 6633
  11. ^ «When Are ICMP Redirects Sent?». Cisco Systems. 2008-06-28. Retrieved 2013-08-15.
  12. ^ D.L. Mills (September 1985). Network Time Protocol (NTP). doi:10.17487/RFC0958. RFC 958. It is evolved from the Time Protocol and the ICMP Timestamp message and is a suitable replacement for both.
  13. ^ «Cisco IOS IP Command Reference, Volume 1 of 4: Addressing and Services, Release 12.3 — IP Addressing and Services Commands: ip mask-reply through ip web-cache». Cisco Systems. Archived from the original on 2013-01-02. Retrieved 2013-01-07.
  14. ^ Extended ICMP to Support Multi-Part Messages. doi:10.17487/RFC4884. RFC 4884.

Sources[edit]

RFCs[edit]

  • RFC 792, Internet Control Message Protocol
  • RFC 950, Internet Standard Subnetting Procedure
  • RFC 1016, Something a Host Could Do with Source Quench: The Source Quench Introduced Delay (SQuID)
  • RFC 1122, Requirements for Internet Hosts – Communication Layers
  • RFC 1716, Towards Requirements for IP Routers
  • RFC 1812, Requirements for IP Version 4 Routers
  • RFC 4884, Extended ICMP to Support Multi-Part Messages

External links[edit]

  • IANA ICMP parameters
  • IANA protocol numbers
  • Explanation of ICMP Redirect Behavior at the Wayback Machine (archived 2015-01-10)

Межсетевой
протокол управляющих сообщений (ICMP
— Internet
Control
Message
Protocol)
разработан для того, чтобы маршрутизаторы
в Интернете сообщали об ошибках или
предоставляли информацию о нестандартных
усло­виях работы сети. Он является
необходимой частью протокола IP.
И обеспе­чивает обратную связь,
оповещение отправителя данных о
проблемах, возни­кающих в коммуникационном
оборудовании.

Протокол
ICMP
— это механизм сообщения об ошибках. Он
обеспечивает маршрутизаторам,
обнаруживающим ошибки, способ сообщения
об ошибке первоначальному источнику.
Хотя спецификация протокола определяет
допус­тимые способы использования
ICMP
и предлагает варианты возможных дей­ствий
в ответ на ошибки, ICMP
не специфицирует полностью действия,
кото­рые необходимо предпринять в
ответ на все возможные ошибки. Таким
образом, ICMP
только сообщает о возникших ошибках
первоначальному источнику; ис­точник
сам должен связать ошибки с конкретными
прикладными программа­ми и предпринять
действия по исправлению ошибок.

Протокол
ICMP
выполняет следующие основные функции:

  • обмен
    тестовыми сообщениями для выяснения
    наличия и активности уз­лов сети;

  • анализ
    достижимости узлов и сброс пакетов,
    направленных к недостижи­мым узлам;

  • изменение
    маршрутов (Redirect);

  • уничтожение
    пакетов с истекшим временем жизни
    (Time-To-Live);

  • синхронизация
    времени в узлах сети;

  • управление
    трафиком (регулирование частоты отправки
    пакетов).

С
точки зрения уровневых протоколов, ICMP
является частью сетевого уровня. Но по
отношению к IP
ICMP
протокол более высокого уровня, так как
он пользуется услугами IP
для доставки своих сообщений. Другими
словами, каждое сообщение ICMP
передается по сети внутри 1Р-дейтаграммы.

ICMP-сообщения
бывают двух видов: сообщение-запрос и
сообщение об ошибке. Сообщение об ошибке
тесно связано с породившей его
дейтаграм­мой и всегда содержит
заголовок этой IP-дейтаграммы
и первые 64 бит ее данных. Это необходимо
для того, чтобы узел-источник смог более
точно проанализировать причину ошибки,
так как все прикладные протоколы стека
TCP/IP содержат наиболее важную информацию
для анализа в первых 8 байт своего
сообщения. Сообщения-запросы передают
информацию об определен­ной сети и
об определенном компьютере или их
используют для диагностичес­ких
целей.

IP-пакеты
с сообщениями ICMP
передаются по сети «на общих основани­ях»,
без приоритетов, поэтому они тоже могут
теряться. В загруженной сети они могут
вызвать дополнительную загрузку
маршрутизаторов, когда потеря сообщения
об ошибке приводит к порождению нового
сообщения и т. д., пока канал связи не
исчерпает своей пропускной способности.
Для того чтобы пре­дотвратить подобные
ситуации, в спецификации четко определены
правила, руководствуясь которыми
компьютер может решить, передавать его
ICMP-
сообщение или нет.

Правило
1:

потеря пакета с ICMP-сообщением
никогда не генерирует ново­го
ICMP-сообщения.

Правило
2:

сообщения об ошибке никогда не генерируются
в ответ на IP-
дейтаграммы с широковещательными или
групповыми адресами, чтобы не вызвать
полную перегрузку сети — широковещательный
шторм (broadcast
storm).

Правило
3
:
при повреждении фрагментированной
дейтаграммы, 1СМР-со- общение отправляют
только после первого поврежденного
фрагмента (так как источник все равно
повторит передачу всей дейтаграммы
целиком).

Доставка
ICMP-пакетов
требует двух уровней инкапсуляции.
ICMP-пакеты
инкапсулируются внутрь IP-дейтаграммы,
которая сама передается по каж­дой
физической сети в поле данных кадра
(рис. 5.29).

Несмотря
на то, что сообщения ICMP
инкапсулируются и посылаются, ис­пользуя
IP,
ICMP
не считают протоколом более высокого
уровня — он является

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

Формат
ICMP-пакетов.
Хотя каждое сообщение ICMP
имеет свой соб­ственный формат, все
они начинаются с трех одинаковых полей:
8-битового целочисленного поля «Тип»,
идентифицирующего сообщение, 8-битового
поля «Код», обеспечивающего более точную
информацию о типе сообщения, и 16­битового
поля «Контрольная сумма» (рис. 5.30). Помимо
того, сообщения ICMP,
сообщающие об ошибках, всегда включают
заголовок и первые 64 бит данных
дейтаграммы, вызвавшей ошибку. Это
необходимо для того, чтобы узел-от­правитель
смог более точно проанализировать
причину ошибки, так как все протоколы
прикладного уровня стека TCP/IP содержат
наиболее важную ин­формацию для
анализа в первых 64 бит своих сообщений.

Сетевые
программы распознают ICMP-сообщения
по двум признакам: зна­чению поля
«Тип» и значению поля «Код». Контрольная
сумма вычисляется не только для
ICMP-заголовка,
но и для всего сообщения.

Таблица
5.12.

Типы сообщений ICMP

Тип

сообщения

ICMP

Описание

0

Ответ
на эхо (Echo
Reply)

3

Узел
назначения недостижим (Destination
Unreachable)

4

Подавление
источника (Source
Quench)

5

Перенаправление
маршрута (Redirect)

8

Запрос
эха (Echo
Request)

9

Информация
о маршрутизаторах (Router
Advertisement)

10

Регистрация
маршрутизатора (Router
Solicitation)

И

Лимит
времени для дейтаграммы превышен
(Time
Exceeded for a Data- gramm)

12

Проблема
с
параметром
пакета
(Parameter Problem on a Datagramm)

13

Запрос
метки времени (Timestamp
Request)

14

Ответ
для метки времени (Timestamp
Reply)

15

Запрос
информации (не действует)

16

Ответ
на запрос информации (не действует)

17

Запрос
маски
адреса
(Address Mask Request)

18

Ответ
на запрос маски адреса (Address
Mask
Reply)

Типы
сообщений ICMP
представлены в табл. 5.12. Рассмотрим
каждое из этих сообщений и его формат
подробнее.

Тестирование
достижимости места назначения. Протоколы
TCP/IP обеспечивают средства, помогающие
сетевым администраторам или пользо­вателям
идентифицировать проблемы в сети.
Пользователь в качестве одного из широко
используемых средств отладки применяют
команду, которая вызы­вает сообщения
ICMP
запроса эха и ответа эха. Компьютер или
маршрутиза­тор посылает сообщение
запроса эха указанному месту назначения.
Любая машина, получившая запрос эха,
генерирует ответ на эхо и возвращает
его пер­воначальному отправителю.
Этот запрос содержит необязательную
область данных; ответ содержит копию
данных, посланных в запросе. Запрос эха
и свя­занный с ним ответ можно
использовать для проверки достижимости
назначе­ния и его способности отвечать
на запросы. Так как и запрос эха, и ответ
на него передаются в IP-дейтаграммах,
успешный прием ответа свидетельству­ет
о работоспособности основных частей
транспортной системы. Во-первых,
программное обеспечение IP
на машине источника выполнило
маршрутиза­цию дейтаграммы. Во-вторых,
промежуточные маршрутизаторы между
ис­точником и получателем работоспособны
и корректно маршрутизируют дей­таграммы.
В-третьих, машина получателя работает
(по крайней мере, она обрабатывает
прерывания) и программное обеспечение,
как IP,
так и ICMP,
выполняет свои функции. И, наконец,
таблицы маршрутов в маршрутизаторах
на всем обратном пути корректны.

Во
многих системах команда, которую
пользователи вызывают для посыл­ки
запроса эха ICMP,
называется ping.
Усложненные версии этой программы
посылают серии запросов эха ICMP,
принимают ответы и выдают статистику
о потерях дейтаграмм. Они позволяют
пользователю указывать длину посы­лаемых
данных и интервалы времени между
запросами. Менее сложные вер­сии
просто посылают запрос эха ICMP
и ждут ответа.

Формат
сообщения запроса эха и ответа эха.

Средства для тестирова­ния достижимости
узлов сети представляют собой очень
простой эхо-прото­кол, включающий
обмен двумя типами сообщений: эхо-запрос
и эхо-ответ. Ком­пьютер или маршрутизатор
посылают по интерсети эхо-запрос, в
котором указывают IP-адрес
узла, достижимость которого нужно
проверить. Узел, по­лучающий эхо-запрос,
формирует и отправляет эхо-ответ и
возвращает сооб­щение узлу — отправителю
запроса. В запросе могут содержаться
некоторые данные, которые должны быть
возвращены в ответе.

Рис.
5.30 иллюстрирует формат сообщений запроса
эха и ответа на запрос эха. Поле
«Необязательные данные» имеет переменную
длину и содержит дан­ные, которые надо
вернуть отправителю. Ответ на эхо всегда
возвращает те же самые данные, что были
получены им в запросе. Поля «Идентификатор»
и «Последовательный номер» отправитель
использует для проверки соответствия
ответов запросам. Значение поля «Тип»
определяет, является ли сообщение
запросом (8) или ответом (0).

Сообщения
о недостижимости назначения.

Когда маршрутизатор не может доставить
IP-дейтаграмму,
он посылает сообщение «назначение
недо­стижимо» первоначальному
отправителю, используя формат, приведенный
на рис. 5.31. Поле «Код» в сообщении о
недостижимости назначения содержит
целое число, которое описывает причину.
Возможные значения представлены в табл.
5.13.

Таблица
5.13.

Коды сообщений о недостижимости

Код

сообщения

Пояснения

0

Сеть
недостижима

1

Компьютер
недостижим

2

Протокол
недостижим

3

Порт
недостижим

4

Необходима
фрагментация

5

Ошибка
при маршрутизации источника

6

Сеть
назначения неизвестна

7

Компьютер
назначения неизвестен

8

Компьютер
источника изолирован

9

Взаимодействие
с сетью назначения административно
запрещено

10

То
же с компьютером назначения

И

Сеть
недостижима из-за класса обслуживания

12

Компьютер
недостижим из-за класса обслуживания

Хотя
протокол ЕР является механизмом
ненадежной доставки, дейтаграм­мы не
уничтожаются просто так. Всякий раз,
когда ошибка мешает маршрути­затору
произвести маршрутизацию или доставку
дейтаграммы, маршрутиза­тор посылает
сообщение о недостижимости назначения
его источнику, а затем уничтожает
дейтаграмму. Ошибки недостижимости
сети обычно являются следствием ошибок
маршрутизации; ошибки недостижимости
компьютера — следствие ошибок при
доставке.

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

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

Управление
потоком дейтаграмм и переполнение сети.
Так как IP-
протокол не устанавливает соединения,
то маршрутизаторы не могут резерви­ровать
память или коммуникационные ресурсы
до получения дейтаграмм. В результате,
трафик может вызвать перегрузку
маршрутизаторов, ситуацию, на­зываемую
переполнением сети (congestion).
Переполнение сети происходит по двум
совершенно разным причинам. Во-первых,
высокоскоростной компью­тер может
генерировать трафик быстрее, чем сеть
может передавать его. На­пример,
представим суперкомпьютер, генерирующий
межсетевой трафик. Дей­таграммам,
посылаемым им, может потребоваться
передача, в конечном счете, по медленной
глобальной сети (WAN),
хотя сам суперкомпьютер может быть
присоединен к высокоскоростной LAN.
Переполнение будет возникать в
мар­шрутизаторе, присоединенном к
глобальной сети, так как дейтаграммы
будут прибывать быстрее, чем их можно
послать. Во-вторых, если большому числу
компьютеров одновременно нужно посылать
дейтаграммы через один марш­рутизатор,
этот маршрутизатор может оказаться
переполненным, хотя ни один источник в
отдельности не вызывает эту проблему.

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

Сообщение
о подавлении источника требует от
источника уменьшить ско­рость передачи
дейтаграмм. Обычно переполненные
маршрутизаторы посы­лают по одному
сообщению о подавлении источника на
каждую удаляемую дейтаграмму или
используют более сложные технологии
выхода из переполне­ния. Формат
подавления источника представлен на
рис. S.32.
Помимо обыч­ных полей ICMP
«Тип», «Код» и «Контрольная сумма» и
неиспользуемого 32-битового поля,
сообщения о подавлении источника имеют
поле, содержащее

префикс
дейтаграммы. Как и в других сообщениях
об ошибках ICMP
поле префикса дейтаграммы содержит
префикс дейтаграммы, вызвавшей этот
зап­рос подавления источника.

Сообщения
ICMP,
вызывающего эффект, обратный подавлению
источника, не существует. Вместо этого,
компьютер, принявший сообщения о
подавлении источника от некоторой
машины, снижает скорость, с которой он
посылает ей дейтаграммы. Это происходит
до тех пор, пока к нему не перестанут
прихо­дить сообщения о подавлении
источника. Затем он постепенно увеличивает
скорость пока снова не получит сообщения
о подавлении источника.

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

При
изменении топологии сети таблицы
маршрутизации в маршрутизаторе или
компьютере могут стать некорректными.
Изменение может быть времен­ным
(например, нужно заменить неисправное
оборудование) или постоянным (например,
когда в межсетевое взаимодействие
включается новая сеть). Мар­шрутизаторы
периодически обмениваются информацией
о маршрутизации, чтобы отслеживать
изменения в сети и своевременно менять
маршруты. Для корректировки поведения
компьютеров маршрутизатор может
использовать сообщение протокола ICMP,
называемое «перенаправлением» (Redirect),
зап­рашивающее изменение маршрута в
таблице маршрутизации компьютера.

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

Преимуществом
схемы перенаправления ICMP
является ее простота: она позволяет
компьютеру знать вначале адрес только
одного маршрутизатора в локальной сети.
Этот начальный маршрутизатор возвращает
сообщение ICMP
о перенаправлении всякий раз, когда
компьютер посылает дейтаграмму, для
которой существует лучший маршрут.
Таблица маршрутизации компьютера
останется маленькой, но содержит
оптимальные маршруты для всех использу­емых
назначений.

Сообщения
о перенаправлении, тем не менее, не
решают проблему распро­странения
информации о маршрутах полностью, так
как они предназначены только для
взаимодействия между маршрутизатором
и компьютером в одной физической сети.
Каждое сообщение о перенаправлении
содержит 32-битовое поле «IP-адрес
маршрутизатора» и поле «Префикс
дейтаграммы», как это по­казано на
рис. 5.33.

Поле
«Межсетевой адрес маршрутизатора»
содержит IP-адрес
маршрути­затора, который должен
использовать компьютер при отправлении
дейтаграм­мы к назначению, указанному
в заголовке дейтаграммы. Поле «Префикс
дей­таграммы» содержит заголовок IP
и следующие 8 байт дейтаграммы, которая
привела к появлению этого сообщения.
Поэтому компьютер, принимающий сообщение
о перенаправлении ICMP,
должен выделить адрес назначения
дей­таграммы из префикса дейтаграммы.
Поле «Код» в сообщении о перенаправ­лении
ICMP
более конкретно указывает, как
интерпретировать адрес назначе­ния,
при этом значения имеют следующий смысл:
0 — перенаправление дейтаграмм для этой
сети (устарело), 1 — перенаправление
дейтаграмм для этого компьютера, 2 —
перенаправление дейтаграмм для этого
типа сервиса и сети, 3 — перенаправление
дейтаграмм для этого типа сервиса и
компьютера. Напомним, что каждый заголовок
IP
указывает тип сервиса, используемого
при маршрутизации. Как правило,
маршрутизаторы посылают запросы
пере­назначения ICMP
только на компьютеры, а не на другие
маршрутизаторы.

Изменение
маршрута является одной из наиболее
интересных функций про­токола ICMP
— по существу, это один из механизмов
автоматической оптими­зации доставки
пакетов и адаптации сетей TCP/IP к изменениям
топологии.

Запросы
«Информация
о маршрутизаторах»
(типы
9 и
10).

Информация
о маршрутизации находится в местных
конфигурационных фай­лах и загружается
оттуда при запуске компьютера. Чтобы
таблица маршрути­зации не содержала
устаревших данных она обновляется
динамически. ICMP-
протокол реализует один из способов ее
обновления.

Существует
2 типа сообщений маршрутизаторов:

  • 9
    — информация о маршрутизации;

  • 10-регистрация
    маршрутизатора.

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

Формат
сообщения «Информация о маршрутизации»
(тип 9) описан в RFC
1256 (рис. 5.34).

В
одном ICMP-сообщении
может содержаться описание нескольких
адре­сов, количество которых указано
в поле «Количество адресов». Поле «Размер
адреса» задает длину адреса в 32-битовых
словах. В настоящее время «Длина поля
адреса» всегда равна 2.

Поле
«Время существования» задает интервал
времени, в течение которо­го информация
еще не устарела. Как правило, это 1800 с.

Поле
«Приоритет» указывает, какой из адресов
следует использовать пер­вым и более
интенсивно. Как правило, чем больше
значение поля, тем выше приоритет.
Маршрутизаторы передают информационные
сообщения широко­вещательно через
случайные интервалы времени. Обычно
через 450…600 с. Поле «Время существования»
можно использовать для уведомления,
что дан­ный маршрутизатор выключается.
При этом содержимое данного поля
уста­навливается равным 0.

Формат
сообщения «Регистрация» (тип 10) представлен
на рис. 5.35.

Запрос
«Регистрация» передается 3 раза с
интервалом 3 с при запуске мар­шрутизатора
и продолжает (при необходимости)
передаваться, пока маршру­тизатор не
получит информационного сообщения с
нужной маршрутной инфор­мацией.

Обнаружение
циклических или слишком длинных путей.

Как было от­мечено выше для защиты
Интернета от перегрузок каждая дейтаграмма
име­ет счетчик времени жизни TTL
(Time-To-Live).
Маршрутизатор декременти­рует счетчик
времени жизни всякий раз, когда он
обрабатывает дейтаграмму, и удаляет
ее, когда счетчик становится нулевым.

Независимо
от того, удалил ли маршрутизатор
дейтаграмму из-за обнуле­ния счетчика
времени жизни или из-за превышения
времени ожидания фраг­ментов
дейтаграммы, он посылает сообщение ICMP
«Лимит времени для дейта­граммы
превышен» источнику дейтаграммы
определенного формата (рис. 5.36).

Поле
«Код» объясняет причину сообщения: 0 —
превышено значение счет­чика времени
жизни; 1 — превышено время ожидания
фрагмента при сборке.

Сообщения
о других ситуациях.

Когда маршрутизатор или компьютер
стал­кивается с проблемой, не
укладывающейся в рамки описанных
сообщений об ошибках ICMP
(например, некорректный заголовок
дейтаграммы), связанной с дейтаграммой,
он посылает сообщение «Проблема с
параметром пакета» первоначальному
отправителю. Такую ситуацию может
вызвать некоррект­ность аргументов
опции. Сообщение, формат которого показан
на рис. 5.37, посылается только в том
случае, если дейтаграмма должна быть
удалена из- за этой ошибки. Для уточнения
места ошибки в дейтаграмме отправитель
ис­пользует поле «Указатель» в
заголовке сообщения для идентификации
октета в дейтаграмме, содержащего
ошибку.

Синхронизация
часов и оценка времени передачи.

Стек протоколов TCP/IP включает несколько
протоколов, которые могут использоваться
для синхрони­зации часов. В сети для
этого используется несколько технологий.
Одна из про­стейших технологий
реализуется сообщениями ICMP
для получения значения времени от другой
машины. Запрашивающая машина посылает
сообщение ICMP
«Запрос метки времени» другой машине,
ожидая, что вторая машина вернет ей
текущее значение времени. Принимающая
машина возвращает «От­вет для метки
времени» машине, выдавшей запрос. Рис.
5.38 иллюстрирует формат сообщений запроса
и ответа временной метки. Поле «Тип»
идентифи­цирует сообщение как запрос
(13) или ответ (14); поля «Идентификатор»
и «Пос­ледовательный номер» используют
источник для связи между ответами и
зап­росами. Оставшиеся поля специфицируют
времена, указанные в миллисекундах
после полуночи, по Гринвичу. Поле
«Временная метка отправителя» заполняет

первоначальный
отправитель перед передачей пакета,
поле «Временная метка приема» заполняется
сразу после приема запроса, а поле
«Временная метка передачи» — непосредственно
перед отправкой ответа.

Компьютеры
используют эти три поля временных меток
для определения ожидаемого времени
передачи между ними и синхронизации
своих часов. Так как ответ включает поле
«Временная метка отправителя», компьютер
может вычислить общее время, требуемое
для передачи запроса к назначению,
фор­мирования ответа на него и
возвращения ответа. Так как ответ
содержит как время прихода запроса на
удаленную машину, так и время выдачи
ответа, ком­пьютер может вычислить
время передачи по сети, а на его основе
— разницу между своими и удаленными
часами. На практике бывает трудно точно
оце­нить время передачи по сети, так
как ГР является технологией с
негарантиро­ванной доставкой,
дейтаграммы могут бьггь потеряны,
задержаны или достав­лены не по
порядку, что ограничивает полезность
сообщений ICMP
о временных метках.

Сообщения
запроса и ответа информации. Сообщения
ICMP
запроса информации и ответа информации
(тип 15 и 16) в настоящее время устарели и
их использовать не рекомендуется. Они
предназначались для обнаружения
компьютерами своих IP-адресов
при загрузке. Сейчас для определения
адреса используют протоколы RARP
и ВООТР.

Получение
маски подсети.

Для применения адресации подсетей
компью­теру надо знать, какие биты их
32-битного IP-адреса
соответствуют физичес­кой сети, а
какие — адресу компьютера. Информация,
требуемая для интерпре­тации адреса,
представляет собой 32-битовую величину,
называемую маской подсети. Чтобы узнать
маску подсети, используемую в локальной
сети, маши­на может послать сообщение
запроса маски адреса маршрутизатору и
полу­чить ответ маски адреса. Машина,
формирующая запрос, может либо послать
сообщение напрямую, если она знает адрес
маршрутизатора, либо послать
ши­роковещательное сообщение, если
не знает его. Рис. 5.39 иллюстрирует фор­мат
сообщений маски адреса. Поле «Тип» в
сообщении маски адреса указыва­ет,
является ли сообщение запросом (17) или
ответом (18). Ответ содержит маску адреса
подсети в поле «Маска адреса». Как
правило, поля «Идентифи­катор» и
«Последовательный номер» позволяют
машине связать ответ с зап­росом.

Недостатком
протокола ICMP
является сохраняющаяся возможность
не­санкционированной посылки ложного
ICMP
Redirect
сообщения о смене марш­рута от имени
маршрутизатора.

����� ��������������
��������� ICMP

�������� ������ ������������
����������� ICMP (Internet Control Message
Protocol)
��������� ��������������
�������� ��������� ���� �� �������,
� �������� ������������ ����������
��� �������� ������-���� IP-������
�� ������� ��������� ����.

����������� ��������� ICMP �� �����
������������ ��������������
��������������, ������� ����������
� �������� ������, � �������
�������� ��������, ��� ��� ���
����� ������� ��� ��������
���������� — ����� ����� � ����
������ ����� ��������� � �����
����������, �� �������� ������
������������� ���������������.

�������� ICMP — ��� �������� ���������
�� �������
, � �� �������� ���������
������
. �������� ���� �����
����������� ��������� �������� ���
����, ����� ������ ������ ��
���������, �� ��� ��������
���������� ICMP �� ����������������.

������ ��������� ��������� ICMP
���������� �� ���� ������ ������ IP.
������ IP � ����������� ICMP
���������������� ����� ��� ��, ���
� ����� ������ ������, ���
�����������, ������� ��� �����
����� ��������. ����� ����, �
����������� ���� ��� �����
�������� �������������� ��������
���������������. ��� ����, ����� ��
�������� ������ ��������� ��
�������, ������ ������� IP,
����������� ��������� ICMP ��
�������, �� ����� ��������� �����
��������� ICMP.

������ ���������
��������� ICMP

���������� ��������� �����
��������� ICMP. ������ ��� ���������
����� ���� ������, ��� ���� ��� ���
���������� � ����� ���� �����:
8-������� ������ �����,
������������� ��� ��������� (TYPE),
8-������� ���� ���� (CODE), �������
�������������� ����������
���������, � 16-������� ����
����������� ����� (CHECKSUM). �����
����, ��������� ICMP ������ ��������
��������� � ������ 64 ���� ������
������ IP, ������� ������ ������. ���
�������� ��� ����, �����
����-����������� ���� ����� �����
���������������� ������� ������,
��� ��� ��� ��������� �����������
������ ����� TCP/IP �������� ��������
������ ���������� ��� ������� �
������ 64 ����� ����� ���������.

���� ���� ����� ����� ���������
��������:

�������� ��� ���������
0 ���-����� (Echo Replay)
3 ���� ����������
���������� (Destination Unreachable)
4 ���������� ���������
(Source Quench)
5 ���������������
�������� (Redirect)
8 ���-������ (Echo Request)
11 ��������� �������
����������� (Time Exceeded for a Datagram)
12 �������� �
���������� ������ (Parameter Problem on a
Datagram)
13 ������ �������
������� (Timestamp Request)
14 ����� �������
������� (Timestamp Replay)
17 ������ ����� (Address Mask
Request)
18 ����� ����� (Address Mask
Replay)

��� ����� �� ������������ �����
���������, �������� ICMP
������������ ����� ���������
����������� ����������, ��������
���� ����� ������.

���-��������

�������� ICMP �������������
������� ��������������� ��������
��� ������������ ������������
����� ����. ��� ��������
������������ ����� ����� �������
���-��������, ���������� �����
����� ������ ���������: ���-������
���-�����. ��������� ���
������������� �������� ��
��������� ���-������, � �������
��������� IP-����� ����,
������������ �������� �����
���������. ����, ������� ��������
���-������, ��������� � ����������
���-����� � ���������� ���������
���� — ����������� �������. �
������� ����� �����������
��������� ������, ������� ������
���� ���������� � ������. ��� ���
���-������ � ���-����� ����������
�� ���� ������ IP-�������, �� ��
�������� �������� ��������
���������� ���������������� ����
������������ ������� ���������.

�� ������ ������������ ��������
������������ ������� ping, �������
������������� ��� ������������
������������ �����. ��� �������
������ �������� ����� ���-��������
� ������������ ���� �
������������� ������������
���������� �� ���������
���-������� � ������� �������
������� ���� �� �������.

��������� �
�������������� ���� ����������

����� ������������� �� �����
�������� ��� ��������� IP-�����, ��
�������� ����, ������������ ����
�����, ��������� «����
���������� ����������» (���
��������� — 3). ��� ���������
�������� � ���� ���� ��������,
���������� �������, �� �������
����� �� ��� ���������. �������
���������� ��������� �������:

��� �������
0 ���� �����������
1 ���� ����������
2 �������� ����������
3 ���� ����������
4 ���������
������������, � ��� DF
����������
5 ������ � ��������,
�������� ����������
6 ���� ����������
����������
7 ���� ����������
����������
8 ����-��������
����������
9 �������������� �
����� ����������
��������������� ���������
10 �������������� �
����� ����������
��������������� ���������
11 ���� ����������� ���
��������� ������ �������
12 ���� ���������� ���
��������� ������ �������

�������������, ������������ ��
�����-���� �������, ��� �� �� �����
�������� IP-����� ����� �� ����,
������ ��������� ICMP-���������
����-���������, � ������ �����
��������� �����. ����� �������
������, ICMP-��������� �������� �����
��������� ��������������� ������ �
��� ������ 64 ���� ���� ������.

���� ��� ���� ���������� �����
���� ����������� ��-�� ���������
������������������� ����������,
��-�� ����, ��� ����������� ������
�������� ����� ����������, � �����
��-�� ����, ��� ������������� ��
����� ������ � �������� � ����
����������.

�������������� ��������� � �����
�������� ���������� ����������
������-���� ��������� �����������
������ � ���� ���������� ��� ��
���������� ��������� �����
���������� UDP ��� TCP � ����
����������.

������ ������������ ���������
�����, ����� ����������� ������ �
���� ����� � ��������� DF,
����������� ������������, �
������������� ���������� �
�������������� �������� �����
������ � ���� �� ��������� MTU
�������, ��� ������ ������.

���������������
��������

���������� ������� � �����������
������ �������� ������������, ���
��� ���������������
��������������� ����, � �
��������������� — �������������,
������������ ������������� �
������� ���������� ������
���������� ����������. ������� �
�������� ������� ��� ���������
��������� ���� ���������� �������
����������� ����� ����������.
����� ����, ��� ������� ������
�������� ������� ����������,
��������, ������ ������ ����������
���������������.

��� ������������� ���������
����������� ������������� �����
������������ ��������� ���������
ICMP, ���������� «���������������
��������» (Redirect).

��� ��������� ���������� � ���
������, ����� ������������� �����,
��� ��������� ���������� �����
��������� ���� ����������
�������������� �������, �� ���� ��
���� �������������� ���������
����, �� �������� ���������� �����
�������� ������� � ���� ����������.

�������� ���������������
��������� ICMP ��������� �����������
��������� � ���������������� �����
������ IP-������ ��� ���������
���������������. � �������
��������� � ���������������
�������������� ����� ��������
���������� ��� ����������� ���
���������� � ���, ������
�������������� ������� ����������
������ ��� ��� ��� ���� ����
����������. �� ���� ��������������
��������� ���������� ������ ���
����� �� ������ �������������.

� ��������� «���������������
��������» �������������
�������� IP-����� ��������������,
������� ����� ������������ �
����������, � ��������� ���������
������ � ������� 64 ������ ��� ����
������. �� ��������� ������ ����
������, ��� ����� ���� ����������
������������ ���������
���������������.

����������
����� | ����������
| ��������� �����

Internet Control Message Protocol (ICMP) is a network layer protocol used to diagnose communication errors by performing an error control mechanism. Since IP does not have an inbuilt mechanism for sending error and control messages. It depends on Internet Control Message Protocol(ICMP) to provide error control. 

ICMP is used for reporting errors and management queries. It is a supporting protocol and is used by network devices like routers for sending error messages and operations information. For example, the requested service is not available or a host or router could not be reached.

Uses of ICMP 

ICMP is used for error reporting if two devices connect over the internet and some error occurs, So, the router sends an ICMP error message to the source informing about the error. For Example, whenever a device sends any message which is large enough for the receiver, in that case, the receiver will drop the message and reply back ICMP message to the source.

Another important use of ICMP protocol is used to perform network diagnosis by making use of traceroute and ping utility. We will discuss them one by one.

Traceroute: Traceroute utility is used to know the route between two devices connected over the internet. It routes the journey from one router to another, and a traceroute is performed to check network issues before data transfer. 

Ping: Ping is a simple kind of traceroute known as the echo-request message, it is used to measure the time taken by data to reach the destination and return to the source, these replies are known as echo-replies messages.

How Does ICMP Work?

ICMP is the primary and important protocol of the IP suite, but ICMP isn’t associated with any transport layer protocol (TCP or UDP) as it doesn’t need to establish a connection with the destination device before sending any message as it is a connectionless protocol.

The working of ICMP is just contrasting with TCP, as TCP is a connection-oriented protocol whereas ICMP is a connectionless protocol. Whenever a connection is established before the message sending, both devices must be ready through a TCP Handshake.

ICMP packets are transmitted in the form of datagrams that contain an IP header with ICMP data. ICMP datagram is similar to a packet, which is an independent data entity. 

ICMP Packet Format

ICMP header comes after IPv4 and IPv6 packet header. 

ICMPv4 Packet Format

ICMPv4 Packet Format

In the ICMP packet format, the first 32 bits of the packet contain three fields:

Type (8-bit): The initial 8-bit of the packet is for message type, it provides a brief description of the message so that receiving network would know what kind of message it is receiving and how to respond to it. Some common message types are as follows:

  • Type 0 – Echo reply
  • Type 3 – Destination unreachable
  • Type 5 – Redirect Message
  • Type 8 – Echo Request
  • Type 11 – Time Exceeded
  • Type 12 – Parameter problem

Code (8-bit): Code is the next 8 bits of the ICMP packet format, this field carries some additional information about the error message and type.

Checksum (16-bit): Last 16 bits are for the checksum field in the ICMP packet header. The checksum is used to check the number of bits of the complete message and enable the ICMP tool to ensure that complete data is delivered.

The next 32 bits of the ICMP Header are Extended Header which has the work of pointing out the problem in IP Message. Byte locations are identified by the pointer which causes the problem message and receiving device looks here for pointing to the problem.

The last part of the ICMP packet is Data or Payload of variable length. The bytes included in IPv4 are 576 bytes and in IPv6, 1280 bytes.

ICMP in DDoS Attacks

In Distributed DOS (DDoS) attacks, attackers provide so much extra traffic to the target, so that it cannot provide service to users. There are so many ways through which an attacker executes these attacks, which are described below.

Ping of Death Attack

Whenever an attacker sends a ping, whose size is greater than the maximum allowable size, oversized packets are broken into smaller parts. When the sender re-assembles it, the size exceeds the limit which causes a buffer overflow and makes the machine freeze. This is simply called a Ping of Death Attack. Newer devices have protection from this attack, but older devices did not have protection from this attack.

ICMP Flood Attack

Whenever the sender sends so many pings that the device on whom the target is done is unable to handle the echo request. This type of attack is called an ICMP Flood Attack. This attack is also called a ping flood attack. It stops the target computer’s resources and causes a denial of service for the target computer.

Smurf Attack

Smurf Attack is a type of attack in which the attacker sends an ICMP packet with a spoofed source IP address. These type of attacks generally works on older devices like the ping of death attack.

Types of ICMP Messages

Type Code        Description
0 – Echo Reply 0 Echo reply
3 – Destination Unreachable 0 Destination network unreachable
1 Destination host unreachable
2 Destination protocol unreachable
3 Destination port unreachable
4 Fragmentation is needed and the DF flag set
5 Source route failed
5 – Redirect Message 0 Redirect the datagram for the network
1 Redirect datagram for the host
2 Redirect the datagram for the Type of Service and Network
3 Redirect datagram for the Service and Host
8 – Echo Request 0 Echo request
9 – Router Advertisement 0 Use to discover the addresses of operational routers
10 – Router Solicitation 0
11 – Time Exceeded 0 Time to live exceeded in transit
1 Fragment reassembly time exceeded.
12 – Parameter Problem 0 The pointer indicates an error.
1 Missing required option
2 Bad length
13 – Timestamp 0 Used for time synchronization
14 – Timestamp Reply 0 Reply to Timestamp message

Source Quench Message

A source quench message is a request to decrease the traffic rate for messages sent to the host destination) or we can say when receiving host detects that the rate of sending packets (traffic rate) to it is too fast it sends the source quench message to the source to slow the pace down so that no packet can be lost. 

Source Quench Message

Source Quench Message

ICMP will take the source IP from the discarded packet and inform the source by sending a source quench message. The source will reduce the speed of transmission so that router will be free from congestion.  

Source Quench Message with Reduced Speed

Source Quench Message with Reduced Speed

When the congestion router is far away from the source the ICMP will send a hop-by-hop source quench message so that every router will reduce the speed of transmission.

Parameter Problem

Whenever packets come to the router then the calculated header checksum should be equal to the received header checksum then only the packet is accepted by the router. 

Parameter Problem

Parameter Problem

If there is a mismatch packet will be dropped by the router. 

ICMP will take the source IP from the discarded packet and inform the source by sending a parameter problem message. 

Time Exceeded Message

Time Exceeded Message

Time Exceeded Message

When some fragments are lost in a network then the holding fragment by the router will be dropped then ICMP will take the source IP from the discarded packet and informs the source, of discarded datagram due to the time to live field reaching zero, by sending the time exceeded message.  

Destination Un-reachable

The destination is unreachable and is generated by the host or its inbound gateway to inform the client that the destination is unreachable for some reason. 

Destination Un-reachable

Destination Un-reachable

There is no necessary condition that only the router gives the ICMP error message time the destination host sends an ICMP error message when any type of failure (link failure, hardware failure, port failure, etc) happens in the network. 

Redirection Message

Redirect requests data packets are sent on an alternate route. The message informs a host to update its routing information (to send packets on an alternate route). 

Example: If the host tries to send data through a router R1 and R1 sends data on a router R2 and there is a direct way from the host to R2. Then R1 will send a redirect message to inform the host that there is the best way to the destination directly through R2 available. The host then sends data packets for the destination directly to R2. 
The router R2 will send the original datagram to the intended destination. 
But if the datagram contains routing information then this message will not be sent even if a better route is available as redirects should only be sent by gateways and should not be sent by Internet hosts. 

Redirection Message

Redirection Message

Whenever a packet is forwarded in the wrong direction later it is re-directed in a current direction then ICMP will send a re-directed message.

For more, you can refer to Types of ICMP (Internet Control Message Protocol) Messages.

FAQs

1. What is ICMP used for?

Internet Control Message Protocol (ICMP) is used for error reporting. Error Reporting by ICMP works by sending messages to the sender from the receiver in the case when data is not received.

2. Is ICMP the same as ping?

ICMP and ping are two different things, but they are somehow related. ICMP is a protocol that manages the messages between the devices and Ping is produced using ICMP.

3. How does ICMP ping work?

ICMP ping is a way to check whether there is a connection established between two devices on the internet. We can check packet loss or any delay that happens within the network with the help of ICMP ping.

Протокол ICMP (Internet Control Message Protocol) — протокол межсетевых управляющих сообщений. 

����� ��������������
��������� ICMP

�������� ������ ������������
����������� ICMP (Internet Control Message
Protocol)
��������� ��������������
�������� ��������� ���� �� �������,
� �������� ������������ ����������
��� �������� ������-���� IP-������
�� ������� ��������� ����.

����������� ��������� ICMP �� �����
������������ ��������������
��������������, ������� ����������
� �������� ������, � �������
�������� ��������, ��� ��� ���
����� ������� ��� ��������
���������� — ����� ����� � ����
������ ����� ��������� � �����
����������, �� �������� ������
������������� ���������������.

�������� ICMP — ��� �������� ���������
�� �������
, � �� �������� ���������
������
. �������� ���� �����
����������� ��������� �������� ���
����, ����� ������ ������ ��
���������, �� ��� ��������
���������� ICMP �� ����������������.

������ ��������� ��������� ICMP
���������� �� ���� ������ ������ IP.
������ IP � ����������� ICMP
���������������� ����� ��� ��, ���
� ����� ������ ������, ���
�����������, ������� ��� �����
����� ��������. ����� ����, �
����������� ���� ��� �����
�������� �������������� ��������
���������������. ��� ����, ����� ��
�������� ������ ��������� ��
�������, ������ ������� IP,
����������� ��������� ICMP ��
�������, �� ����� ��������� �����
��������� ICMP.

������ ���������
��������� ICMP

���������� ��������� �����
��������� ICMP. ������ ��� ���������
����� ���� ������, ��� ���� ��� ���
���������� � ����� ���� �����:
8-������� ������ �����,
������������� ��� ��������� (TYPE),
8-������� ���� ���� (CODE), �������
�������������� ����������
���������, � 16-������� ����
����������� ����� (CHECKSUM). �����
����, ��������� ICMP ������ ��������
��������� � ������ 64 ���� ������
������ IP, ������� ������ ������. ���
�������� ��� ����, �����
����-����������� ���� ����� �����
���������������� ������� ������,
��� ��� ��� ��������� �����������
������ ����� TCP/IP �������� ��������
������ ���������� ��� ������� �
������ 64 ����� ����� ���������.

���� ���� ����� ����� ���������
��������:

�������� ��� ���������
0 ���-����� (Echo Replay)
3 ���� ����������
���������� (Destination Unreachable)
4 ���������� ���������
(Source Quench)
5 ���������������
�������� (Redirect)
8 ���-������ (Echo Request)
11 ��������� �������
����������� (Time Exceeded for a Datagram)
12 �������� �
���������� ������ (Parameter Problem on a
Datagram)
13 ������ �������
������� (Timestamp Request)
14 ����� �������
������� (Timestamp Replay)
17 ������ ����� (Address Mask
Request)
18 ����� ����� (Address Mask
Replay)

��� ����� �� ������������ �����
���������, �������� ICMP
������������ ����� ���������
����������� ����������, ��������
���� ����� ������.

���-��������

�������� ICMP �������������
������� ��������������� ��������
��� ������������ ������������
����� ����. ��� ��������
������������ ����� ����� �������
���-��������, ���������� �����
����� ������ ���������: ���-������
���-�����. ��������� ���
������������� �������� ��
��������� ���-������, � �������
��������� IP-����� ����,
������������ �������� �����
���������. ����, ������� ��������
���-������, ��������� � ����������
���-����� � ���������� ���������
���� — ����������� �������. �
������� ����� �����������
��������� ������, ������� ������
���� ���������� � ������. ��� ���
���-������ � ���-����� ����������
�� ���� ������ IP-�������, �� ��
�������� �������� ��������
���������� ���������������� ����
������������ ������� ���������.

�� ������ ������������ ��������
������������ ������� ping, �������
������������� ��� ������������
������������ �����. ��� �������
������ �������� ����� ���-��������
� ������������ ���� �
������������� ������������
���������� �� ���������
���-������� � ������� �������
������� ���� �� �������.

��������� �
�������������� ���� ����������

����� ������������� �� �����
�������� ��� ��������� IP-�����, ��
�������� ����, ������������ ����
�����, ��������� «����
���������� ����������» (���
��������� — 3). ��� ���������
�������� � ���� ���� ��������,
���������� �������, �� �������
����� �� ��� ���������. �������
���������� ��������� �������:

��� �������
0 ���� �����������
1 ���� ����������
2 �������� ����������
3 ���� ����������
4 ���������
������������, � ��� DF
����������
5 ������ � ��������,
�������� ����������
6 ���� ����������
����������
7 ���� ����������
����������
8 ����-��������
����������
9 �������������� �
����� ����������
��������������� ���������
10 �������������� �
����� ����������
��������������� ���������
11 ���� ����������� ���
��������� ������ �������
12 ���� ���������� ���
��������� ������ �������

�������������, ������������ ��
�����-���� �������, ��� �� �� �����
�������� IP-����� ����� �� ����,
������ ��������� ICMP-���������
����-���������, � ������ �����
��������� �����. ����� �������
������, ICMP-��������� �������� �����
��������� ��������������� ������ �
��� ������ 64 ���� ���� ������.

���� ��� ���� ���������� �����
���� ����������� ��-�� ���������
������������������� ����������,
��-�� ����, ��� ����������� ������
�������� ����� ����������, � �����
��-�� ����, ��� ������������� ��
����� ������ � �������� � ����
����������.

�������������� ��������� � �����
�������� ���������� ����������
������-���� ��������� �����������
������ � ���� ���������� ��� ��
���������� ��������� �����
���������� UDP ��� TCP � ����
����������.

������ ������������ ���������
�����, ����� ����������� ������ �
���� ����� � ��������� DF,
����������� ������������, �
������������� ���������� �
�������������� �������� �����
������ � ���� �� ��������� MTU
�������, ��� ������ ������.

���������������
��������

���������� ������� � �����������
������ �������� ������������, ���
��� ���������������
��������������� ����, � �
��������������� — �������������,
������������ ������������� �
������� ���������� ������
���������� ����������. ������� �
�������� ������� ��� ���������
��������� ���� ���������� �������
����������� ����� ����������.
����� ����, ��� ������� ������
�������� ������� ����������,
��������, ������ ������ ����������
���������������.

��� ������������� ���������
����������� ������������� �����
������������ ��������� ���������
ICMP, ���������� «���������������
��������» (Redirect).

��� ��������� ���������� � ���
������, ����� ������������� �����,
��� ��������� ���������� �����
��������� ���� ����������
�������������� �������, �� ���� ��
���� �������������� ���������
����, �� �������� ���������� �����
�������� ������� � ���� ����������.

�������� ���������������
��������� ICMP ��������� �����������
��������� � ���������������� �����
������ IP-������ ��� ���������
���������������. � �������
��������� � ���������������
�������������� ����� ��������
���������� ��� ����������� ���
���������� � ���, ������
�������������� ������� ����������
������ ��� ��� ��� ���� ����
����������. �� ���� ��������������
��������� ���������� ������ ���
����� �� ������ �������������.

� ��������� «���������������
��������» �������������
�������� IP-����� ��������������,
������� ����� ������������ �
����������, � ��������� ���������
������ � ������� 64 ������ ��� ����
������. �� ��������� ������ ����
������, ��� ����� ���� ����������
������������ ���������
���������������.

����������
����� | ����������
| ��������� �����

Internet Control Message Protocol (ICMP) is a network layer protocol used to diagnose communication errors by performing an error control mechanism. Since IP does not have an inbuilt mechanism for sending error and control messages. It depends on Internet Control Message Protocol(ICMP) to provide error control. 

ICMP is used for reporting errors and management queries. It is a supporting protocol and is used by network devices like routers for sending error messages and operations information. For example, the requested service is not available or a host or router could not be reached.

Uses of ICMP 

ICMP is used for error reporting if two devices connect over the internet and some error occurs, So, the router sends an ICMP error message to the source informing about the error. For Example, whenever a device sends any message which is large enough for the receiver, in that case, the receiver will drop the message and reply back ICMP message to the source.

Another important use of ICMP protocol is used to perform network diagnosis by making use of traceroute and ping utility. We will discuss them one by one.

Traceroute: Traceroute utility is used to know the route between two devices connected over the internet. It routes the journey from one router to another, and a traceroute is performed to check network issues before data transfer. 

Ping: Ping is a simple kind of traceroute known as the echo-request message, it is used to measure the time taken by data to reach the destination and return to the source, these replies are known as echo-replies messages.

How Does ICMP Work?

ICMP is the primary and important protocol of the IP suite, but ICMP isn’t associated with any transport layer protocol (TCP or UDP) as it doesn’t need to establish a connection with the destination device before sending any message as it is a connectionless protocol.

The working of ICMP is just contrasting with TCP, as TCP is a connection-oriented protocol whereas ICMP is a connectionless protocol. Whenever a connection is established before the message sending, both devices must be ready through a TCP Handshake.

ICMP packets are transmitted in the form of datagrams that contain an IP header with ICMP data. ICMP datagram is similar to a packet, which is an independent data entity. 

ICMP Packet Format

ICMP header comes after IPv4 and IPv6 packet header. 

ICMPv4 Packet Format

ICMPv4 Packet Format

In the ICMP packet format, the first 32 bits of the packet contain three fields:

Type (8-bit): The initial 8-bit of the packet is for message type, it provides a brief description of the message so that receiving network would know what kind of message it is receiving and how to respond to it. Some common message types are as follows:

  • Type 0 – Echo reply
  • Type 3 – Destination unreachable
  • Type 5 – Redirect Message
  • Type 8 – Echo Request
  • Type 11 – Time Exceeded
  • Type 12 – Parameter problem

Code (8-bit): Code is the next 8 bits of the ICMP packet format, this field carries some additional information about the error message and type.

Checksum (16-bit): Last 16 bits are for the checksum field in the ICMP packet header. The checksum is used to check the number of bits of the complete message and enable the ICMP tool to ensure that complete data is delivered.

The next 32 bits of the ICMP Header are Extended Header which has the work of pointing out the problem in IP Message. Byte locations are identified by the pointer which causes the problem message and receiving device looks here for pointing to the problem.

The last part of the ICMP packet is Data or Payload of variable length. The bytes included in IPv4 are 576 bytes and in IPv6, 1280 bytes.

ICMP in DDoS Attacks

In Distributed DOS (DDoS) attacks, attackers provide so much extra traffic to the target, so that it cannot provide service to users. There are so many ways through which an attacker executes these attacks, which are described below.

Ping of Death Attack

Whenever an attacker sends a ping, whose size is greater than the maximum allowable size, oversized packets are broken into smaller parts. When the sender re-assembles it, the size exceeds the limit which causes a buffer overflow and makes the machine freeze. This is simply called a Ping of Death Attack. Newer devices have protection from this attack, but older devices did not have protection from this attack.

ICMP Flood Attack

Whenever the sender sends so many pings that the device on whom the target is done is unable to handle the echo request. This type of attack is called an ICMP Flood Attack. This attack is also called a ping flood attack. It stops the target computer’s resources and causes a denial of service for the target computer.

Smurf Attack

Smurf Attack is a type of attack in which the attacker sends an ICMP packet with a spoofed source IP address. These type of attacks generally works on older devices like the ping of death attack.

Types of ICMP Messages

Type Code        Description
0 – Echo Reply 0 Echo reply
3 – Destination Unreachable 0 Destination network unreachable
1 Destination host unreachable
2 Destination protocol unreachable
3 Destination port unreachable
4 Fragmentation is needed and the DF flag set
5 Source route failed
5 – Redirect Message 0 Redirect the datagram for the network
1 Redirect datagram for the host
2 Redirect the datagram for the Type of Service and Network
3 Redirect datagram for the Service and Host
8 – Echo Request 0 Echo request
9 – Router Advertisement 0 Use to discover the addresses of operational routers
10 – Router Solicitation 0
11 – Time Exceeded 0 Time to live exceeded in transit
1 Fragment reassembly time exceeded.
12 – Parameter Problem 0 The pointer indicates an error.
1 Missing required option
2 Bad length
13 – Timestamp 0 Used for time synchronization
14 – Timestamp Reply 0 Reply to Timestamp message

Source Quench Message

A source quench message is a request to decrease the traffic rate for messages sent to the host destination) or we can say when receiving host detects that the rate of sending packets (traffic rate) to it is too fast it sends the source quench message to the source to slow the pace down so that no packet can be lost. 

Source Quench Message

Source Quench Message

ICMP will take the source IP from the discarded packet and inform the source by sending a source quench message. The source will reduce the speed of transmission so that router will be free from congestion.  

Source Quench Message with Reduced Speed

Source Quench Message with Reduced Speed

When the congestion router is far away from the source the ICMP will send a hop-by-hop source quench message so that every router will reduce the speed of transmission.

Parameter Problem

Whenever packets come to the router then the calculated header checksum should be equal to the received header checksum then only the packet is accepted by the router. 

Parameter Problem

Parameter Problem

If there is a mismatch packet will be dropped by the router. 

ICMP will take the source IP from the discarded packet and inform the source by sending a parameter problem message. 

Time Exceeded Message

Time Exceeded Message

Time Exceeded Message

When some fragments are lost in a network then the holding fragment by the router will be dropped then ICMP will take the source IP from the discarded packet and informs the source, of discarded datagram due to the time to live field reaching zero, by sending the time exceeded message.  

Destination Un-reachable

The destination is unreachable and is generated by the host or its inbound gateway to inform the client that the destination is unreachable for some reason. 

Destination Un-reachable

Destination Un-reachable

There is no necessary condition that only the router gives the ICMP error message time the destination host sends an ICMP error message when any type of failure (link failure, hardware failure, port failure, etc) happens in the network. 

Redirection Message

Redirect requests data packets are sent on an alternate route. The message informs a host to update its routing information (to send packets on an alternate route). 

Example: If the host tries to send data through a router R1 and R1 sends data on a router R2 and there is a direct way from the host to R2. Then R1 will send a redirect message to inform the host that there is the best way to the destination directly through R2 available. The host then sends data packets for the destination directly to R2. 
The router R2 will send the original datagram to the intended destination. 
But if the datagram contains routing information then this message will not be sent even if a better route is available as redirects should only be sent by gateways and should not be sent by Internet hosts. 

Redirection Message

Redirection Message

Whenever a packet is forwarded in the wrong direction later it is re-directed in a current direction then ICMP will send a re-directed message.

For more, you can refer to Types of ICMP (Internet Control Message Protocol) Messages.

FAQs

1. What is ICMP used for?

Internet Control Message Protocol (ICMP) is used for error reporting. Error Reporting by ICMP works by sending messages to the sender from the receiver in the case when data is not received.

2. Is ICMP the same as ping?

ICMP and ping are two different things, but they are somehow related. ICMP is a protocol that manages the messages between the devices and Ping is produced using ICMP.

3. How does ICMP ping work?

ICMP ping is a way to check whether there is a connection established between two devices on the internet. We can check packet loss or any delay that happens within the network with the help of ICMP ping.

Протокол ICMP (Internet Control Message Protocol) — протокол межсетевых управляющих сообщений. 

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

Информация о возникающих ошибках в сети передается по протоколу ICMP. А также протокол ICMP может использоваться для диагностики работы в сети даже, когда в ней не возникают ошибки. Так как IP предоставляет сервис без гарантии доставки, то сообщение об ошибках ICMP не обязаны обрабатываться ни протоколом ICMP ни протоколом IP.  

Формат заголовка ICMP

Рассмотрим формат пакета ICMP. Первое поле в заголовке тип сообщения. Оно говорит о том, что произошло в сети, какая ошибка или какое действие по диагностике пытаются выполнить.

Формат заголовка ICMP

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

Типы ICMP — сообщений

Самое важно в пакете ICMP это тип сообщений. Именно тип, говорит о том, что произошло в сети. Есть 2 вида ICMP сообщений. Первый вид это запрос-ответ.

Типы ICMP - сообщений

  • Например, тип 0 и тип 8 это эхо-ответ и эхо-запрос, которые используются для проверки доступности компьютера в сети. 
  • Тип 13 и 14 запрос и ответ отметки времени. Эти запросы используются для проверки быстродействия сети. Другой вид это сообщение без запроса. 
  • Тип 3 это сообщение об ошибке узел назначения недостижим. 
  • Тип 5 сообщение о новом маршруте, который позволяет быстрее попасть к необходимой сети. 
  • Тип 9 сообщение о маршрутизаторе. Маршрутизаторы в сети периодически рассылают такие сообщения, чтобы компьютеры, которые находятся в сети могли узнать, какие есть маршрутизаторы. 
  • Тип 10 запрос сообщения о маршрутизаторе, если компьютер только что подключился к сети, он может не дожидаться периодического сообщения от маршрутизаторов, отправить такой запрос и маршрутизатор сразу отправит ответ о себе. 
  • Сообщение с типом 11 используется если маршрутизатор отбросил пакет время жизни которого истекло, как правило такая ситуация возникает, если в сети появилась петля.
  • Сообщение с типом 12 — проблемы с параметрами, говорит о том, что в заголовке IP какая-то ошибка и маршрутизатор не может отправить такой пакет. 

Коды ICMP — сообщений 

Следующее поле в заголовке ICMP это код сообщения. Ниже представлено несколько возможных кодов для типа сообщения 3 — узел назначения недостижим. Какие могут быть причины? Причины перечислены ниже на картинке. 

Коды ICMP - сообщений

Применение ICMP

Большая часть пакетов ICMP формируется и отправляется автоматически сетевым оборудованиям. Но некоторые типы сообщений формируются утилитами, которые применяются для диагностики сети. Рассмотрим утилиты ping и traceroute (в Windows tracert)

Утилита ping

Утилита ping используется, чтобы проверить доступность компьютера в сети. Возможно подключиться к этому компьютеру или нельзя. Ping использует это-протокол ICMP. Компьютер, который хочет проверить доступность другого, отправляет эхо-запрос (тип=8, код=0).

Утилита ping

Компьютер, который получил такой запрос, в ответ отправляет эхо-ответ ICMP с типом 0, если эхо-ответ не пришел, значит установить с компьютером соединение по сети невозможно.

Утилита ping

Пример использования утилиты ping для проверки возможности подключиться к сайту ВКонтакте. По умолчанию утилита ping запускает 4 эхо-запроса и для каждого эхо-запроса получен эхо-ответ. В ответе указывается некоторая диагностическая информация.

ping пример

Утилита traceroute

Утилита traceroute позволяет определить маршрут от отправителя к получателю. Под маршрутом имеется в виду перечень всех маршрутизаторов через которые проходит пакет. 

Пример работы утилиты traceroute ее windows вариант tracert для определения маршрута к сайту ВКонтакте. 

Пример Утилита traceroute

Работа утилиты traceroute 

Как утилита traceroute узнает маршрутизатор? Для этого утилита использует ICMP сообщения время жизни истекло. Чтобы этого достичь, сначала отправляется сообщение у которого время жизни установлено в единицу TTL=1.

Работа утилиты traceroute

Пакет доходит до первого маршрутизатора, маршрутизатор уменьшает время жизни TTL=0 и маршрутизатор отбрасывает пакет.

Работа утилиты traceroute

И генерирует сообщение об ошибке ICMP с типом 11, код 0 время жизни истекло. Утилита traceroute из заголовка IP пакета в которого вложен ICMP извлекает IP-адрес маршрутизатора.

Работа утилиты traceroute

На следующем этапе отправляется пакет с временем жизни равным двум TTL=2. 

Работа утилиты traceroute

На первом маршрутизаторе время жизни уменьшается до единицы и пакет переходит на второй маршрутизатор.

Работа утилиты traceroute

Второй маршрутизатор снова уменьшает время на 1, время жизни становится нулем. Пакет отбрасывается и уже второй маршрутизатор отправляет сообщение время жизни истекло. Утилита traceroute извлекает адрес второго маршрутизатора из IP заголовка этого сообщения. 

Работа утилиты traceroute

И так происходит до тех пор пока пакет не дойдет до узла назначения. 

Заключение

Рассмотрели протокол ICMP протокол межсетевых управляющих сообщений. Протокол ICMP используется для сообщения об ошибках, которые происходят в сети  и для тестирования работоспособности сети. 

Понравилась статья? Поделить с друзьями:
  • Icloud для windows во время аутентификации произошла ошибка icloud
  • Icloud во время аутентификации произошла ошибка повторите попытку
  • Icloud windows 10 ошибка 101
  • Iclebo c8 ошибка как исправить
  • Iclebo arte ошибка c8 что это