Type 0 — Echo Reply
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 1 — Unassigned
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 2 — Unassigned
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 3 — Destination Unreachable
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Net Unreachable | [RFC792] |
1 | Host Unreachable | [RFC792] |
2 | Protocol Unreachable | [RFC792] |
3 | Port Unreachable | [RFC792] |
4 | Fragmentation Needed and Don’t Fragment was Set |
[RFC792] |
5 | Source Route Failed | [RFC792] |
6 | Destination Network Unknown | [RFC1122] |
7 | Destination Host Unknown | [RFC1122] |
8 | Source Host Isolated | [RFC1122] |
9 | Communication with Destination Network is Administratively Prohibited |
[RFC1122] |
10 | Communication with Destination Host is Administratively Prohibited |
[RFC1122] |
11 | Destination Network Unreachable for Type of Service |
[RFC1122] |
12 | Destination Host Unreachable for Type of Service |
[RFC1122] |
13 | Communication Administratively Prohibited | [RFC1812] |
14 | Host Precedence Violation | [RFC1812] |
15 | Precedence cutoff in effect | [RFC1812] |
Type 4 — Source Quench (Deprecated)
- Reference
- [RFC792][RFC6633]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 5 — Redirect
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Redirect Datagram for the Network (or subnet) | |
1 | Redirect Datagram for the Host | |
2 | Redirect Datagram for the Type of Service and Network | |
3 | Redirect Datagram for the Type of Service and Host |
Type 6 — Alternate Host Address (Deprecated)
- Reference
- [JBP][RFC6918]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Alternate Address for Host |
Type 7 — Unassigned
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 8 — Echo
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 9 — Router Advertisement
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC1256][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Normal router advertisement | [RFC3344] |
16 | Does not route common traffic | [RFC3344] |
Type 10 — Router Selection
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC1256][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 11 — Time Exceeded
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Time to Live exceeded in Transit | |
1 | Fragment Reassembly Time Exceeded |
Type 12 — Parameter Problem
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Pointer indicates the error | |
1 | Missing a Required Option | [RFC1108] |
2 | Bad Length |
Type 13 — Timestamp
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 14 — Timestamp Reply
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC792][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 15 — Information Request (Deprecated)
- Reference
- [RFC792][RFC6918]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 16 — Information Reply (Deprecated)
- Reference
- [RFC792][RFC6918]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 17 — Address Mask Request (Deprecated)
- Reference
- [RFC950][RFC6918]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 18 — Address Mask Reply (Deprecated)
- Reference
- [RFC950][RFC6918]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Code |
Type 19 — Reserved (for Security)
- Reference
- [Solo]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Types 20-29 — Reserved (for Robustness Experiment)
- Reference
- [ZSu]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 30 — Traceroute (Deprecated)
- Reference
- [RFC1393][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 31 — Datagram Conversion Error (Deprecated)
- Reference
- [RFC1475][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 32 — Mobile Host Redirect (Deprecated)
- Reference
- [David_Johnson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 33 — IPv6 Where-Are-You (Deprecated)
- Reference
- [Simpson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 34 — IPv6 I-Am-Here (Deprecated)
- Reference
- [Simpson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 35 — Mobile Registration Request (Deprecated)
- Reference
- [Simpson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 36 — Mobile Registration Reply (Deprecated)
- Reference
- [Simpson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 37 — Domain Name Request (Deprecated)
- Reference
- [RFC1788][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 38 — Domain Name Reply (Deprecated)
- Reference
- [RFC1788][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 39 — SKIP (Deprecated)
- Reference
- [Markson][RFC6918]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 40 — Photuris
- Registration Procedure(s)
-
IESG Approval or Standards Action
- Reference
- [RFC2521][RFC2780]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Bad SPI | |
1 | Authentication Failed | |
2 | Decompression Failed | |
3 | Decryption Failed | |
4 | Need Authentication | |
5 | Need Authorization |
Type 41 — ICMP messages utilized by experimental mobility protocols such as Seamoby
- Registration Procedure(s)
-
Specification Required or IESG Approval
- Expert(s)
-
Unassigned
- Reference
- [RFC4065]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 42 — Extended Echo Request
- Registration Procedure(s)
-
First Come First Served
- Reference
- [RFC8335]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Error | [RFC8335] |
1-255 | Unassigned |
Type 43 — Extended Echo Reply
- Registration Procedure(s)
-
First Come First Served
- Reference
- [RFC8335]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | No Error | [RFC8335] |
1 | Malformed Query | [RFC8335] |
2 | No Such Interface | [RFC8335] |
3 | No Such Table Entry | [RFC8335] |
4 | Multiple Interfaces Satisfy Query | [RFC8335] |
5-255 | Unassigned |
Types 44-252 — Unassigned
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 253 — RFC3692-style Experiment 1 [1]
- Registration Procedure(s)
-
Standards Action or IESG Approval
- Reference
- [RFC4727]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Type 254 — RFC3692-style Experiment 2 [1]
- Registration Procedure(s)
-
Standards Action or IESG Approval
- Reference
- [RFC4727]
Codes | Description | Reference |
---|---|---|
No registrations at this time. |
Sub-types — Class 1 — MPLS Label Stack Class
- Registration Procedure(s)
-
First Come First Served
- Reference
- [RFC4950]
- Available Formats
-
CSV
C-Type (Value) | Description | Reference |
---|---|---|
0 | Reserved | [RFC4950] |
1 | Incoming MPLS Label Stack | [RFC4950] |
2-246 | Unassigned | |
247-255 | Reserved for private use | [RFC4950] |
Sub-types — Class 2 — Interface Information Object
- Reference
- [RFC5837]
- Available Formats
-
CSV
C-Type (Value) | Description | Reference |
---|---|---|
0-1 | Interface Role field | [RFC5837] |
2 | Unallocated — allocatable with Standards Action | [RFC5837] |
3 | Unallocated — allocatable with Standards Action | [RFC5837] |
4 | ifIndex included | [RFC5837] |
5 | IP Address Sub-object included | [RFC5837] |
6 | Name Sub-object included | [RFC5837] |
7 | MTU included | [RFC5837] |
Sub-types — Class 2 — Interface Information Object — Interface Roles
- Available Formats
-
CSV
Value | Description | Reference |
---|---|---|
0 | Incoming IP Interface | [RFC5837] |
1 | Sub-IP Component of Incoming IP Interface | [RFC5837] |
2 | Outgoing IP Interface | [RFC5837] |
3 | IP Next-hop | [RFC5837] |
Sub-types — Class 3 — Interface Identification Object
- Registration Procedure(s)
-
First Come First Served
- Reference
- [RFC8335]
- Available Formats
-
CSV
Codes | Description | Reference |
---|---|---|
0 | Reserved | [RFC8335] |
1 | Identifies Interface By Name | [RFC8335] |
2 | Identifies Interface By Index | [RFC8335] |
3 | Identifies Interface By Address | [RFC8335] |
4-255 | Unassigned |
Sub-types — Class 4 — Extended Information
- Registration Procedure(s)
-
Standards Action
- Reference
- [RFC8883]
- Available Formats
-
CSV
Value | Description | Reference |
---|---|---|
0 | Reserved | [RFC8883] |
1 | Pointer | [RFC8883] |
Last Updated: [last-modified] (UTC)
Types Summary
The 4-byte ICMP header contains an 8-bit type field, which defines the ICMP type. The type determines what the ICMP packet is used for. Depending on the type, the 8-bit code field may also be used, which contains additional information. If the type does not have any codes defined, the code field is set to zero.
For more general information on ICMP, see ICMP for IPv4.
Below is a table of all currently defined ICMP types. Note that some of these are IPv4 or IPv6 specific.
Type | Description | Status |
---|---|---|
0 | Echo Reply | |
1-2 | Unassigned | |
3 | Destination Unreachable | |
4 | Source Quench | Deprecated |
5 | Redirect | |
6 | Alternate Host Address | Deprecated |
7 | Unassigned | |
8 | Echo | |
9 | Router Advertisement | |
10 | Router Solicitation | |
11 | Time Exceeded | |
12 | Parameter Problem | |
13 | Timestamp | |
14 | Timestamp Reply | |
15 | Information Request | Deprecated |
16 | Information Reply | Deprecated |
17 | Address Mask Request | Deprecated |
18 | Address Mask Reply | Deprecated |
19-29 | Reserved | |
30 | Traceroute | Deprecated |
31 | Datagram Conversion Error | Deprecated |
32 | Mobile Host Redirect | Deprecated |
33 | IPv6 Where-Are-You | Deprecated |
34 | IPv6 I-Am-Here | Deprecated |
35 | Mobile Registration Request | Deprecated |
36 | Mobile Registration Reply | Deprecated |
37 | Domain Name Request | Deprecated |
38 | Domain Name Reply | Deprecated |
39 | SKIP | Deprecated |
40 | Photuris | |
41 | Experimental | |
42-252 | Unassigned | |
253-254 | Reserved |
Active Types
There are many types which have been deprecated, or are reserved for some reason. The ones that are still active are outlined here.
Echo and Echo-Reply
ICMP echo and echo-reply are commonly use in the ping application. This sends an ICMP echo to a host, which returns an ICMP echo-reply. If unsuccessful, the request will either time out, or a device along the path will reply with some type of ICMP error message.
An echo packet has type 8 set in the ICMP header, and the reply uses type zero. Neither have any codes defined, so the code field in the header is always set to zero.
The second four bytes of the header includes two 16-bit fields; The Identifier and the Sequence. These are used to match a particular echo with the echo-reply. These fields are used differently depending on implementation. For example, Linux sets a unique identifier for each process, while Windows uses a single identifier for all processes (the value is selected at boot time). Both Linux and Windows use an incrementing sequence value for each echo.
The data area of the packet is used for padding out to a particular size. The padding is usually made up of ASCII characters. When a host receives an echo packet, its echo-reply packet must use the same data payload as the original echo.
The size of the data area will vary, based on the MTU of the LAN, or based on manually specified sizes. By default, the packet has to fit into the MTU of the LAN that the source host is part of. However, keep in mind that this does not mean that the packet will definitley fit into the MTU size of all network segments along the path from source to destination. If it is too large, the packet will need to be fragmented.
Below is an excerpt from a packet capture that was run during a successful ping. Notice that the type is set to zero, which is the echo-reply.
Destination Unreachable
Destination Unreachable messages are used to inform a sender that a packet could not be delivered to an endpoint. This message is sent unsollicited from the end host or an interim device, such as a router. In this context, unsolicited means that the source didn’t send an ICMP query and expect a response (such as with echo and echo-reply), another device simply informs the sender of the problem.
When this error is raised, a code is included (as shown in the table below), to give the sender a clue as to what is wrong. Additionally, the data field (after the full 8-byte header) includes a part of the original packet that failed. This is included so the sender can match the error to the process that generated the original packet.
Code | Description | Notes |
---|---|---|
0 | Net Unreachable | The network could not be found. May indicate a routing problem |
1 | Host Unreachable | The network was found, but the host was not. May be a routing problem, or the host is off |
2 | Protocol Unreachable | The specified protocol is invalid for this host |
3 | Port unreachable | The specified destination port is invalid for this host |
4 | Fragmentation Needed, and DF was set | The packet is larger than the MTU for the network, and the packet cannot be fragmented |
5 | Source route failed | Used if a source route is specified, but a router could not forward the packet |
6 | Destination network unknown | No longer used (Code 0 used instead) |
7 | Destination host unknown | Generated by a router local to the destination host. Indicates that the address is bad |
8 | Source host isolated | No longer used |
9 | Communication with destination network is administratively prohibited | The source device is not allowed to send to the destination network |
10 | Communication with destination host is administratively prohibited | The source can send to the destination network, but not the specified host |
11 | Destination network unreachable for type of service | The destination network cannot honour the value in the ToS field |
12 | Destination host unreachable for type of service | The destination host cannot honour the value in the ToS field |
13 | Communication administratively prohibited | Some sort of filtering is blocking the packet based on its content |
14 | Host precedence violation | Sent by the first-hop router. This happens if the precedence value in the ToS field is not allowed |
15 | Precedence cutoff in effect | Sent by a router if the precedence in the ToS field is lower than permitted for that network |
Generally, codes 0-5 seem to be the most common. Code 2 (protocol unreachable) and code 3 (port unreachable) are sent by the end host, and indicates that there is a problem on the host itself, such as port not open, process not running and so on.
Code 0 (Net Unreachable), code 1 (Host Unreachable), and code 5 (Source Route Failed) are sent by an interim router, and usually suggest that there is a routing or firewall problem.
Code 4 (Fragmentation needed and DF bit set) is also sent by an interim router. This happens if a packet is larger than the MTU for the interim network, however fragmentation into smaller packets is not allowed as the Dont Fragment bit in the IP header is set.
Below is a packet capture of an unreachable message. Notice that the type is set to 3 (Destination Unreachable), and in this case the code is 1 (Host Unreachable). Notice that the original packet (an ICMP Echo in this case) has been included in the data area of the ICMP message.
This error was generated when a host send a ping, but an interim router didn’t have a route to that host. Remember that the ICMP message will only be received if the interim router also has a route back to the source.
Redirect
An ICMP redirect message assists in making routing more efficient. In a case where a host has a default gateway, and the default gateway knows that a different local router if better for the network that the host is trying to reach, the gateway will send a redirect to the host, telling the host to use that router from now on. This may apply to all traffic to the particular destination network, or only traffic for the specific destination host.
It is important to understand that this helps with routing efficiency, but is not used to populate routing tables.
As shown in the packet capture below, the IP address of the ‘better’ router is included in the second 4 bytes of the header. The data section is populated with the first 8 bytes of the original packet, so the sender can match the message to the originating process.
Code | Description | Notes |
---|---|---|
0 | Redirect datagram for the network (or subnet) | Redirect future packets for all hosts on the destination network |
1 | Redirect datagram for the host | Redirect future packets for this host only |
2 | Redirect datagram for the type of service and network | No longer used |
3 | Redirect datagram for the type of service and host | No longer used |
Router Advertisement and Solicitation
The Router Solicitation and Router Advertisement messages are used as part of the Internet Router Discovery Protocol (IRDP), which is defined in RFC1256. This is a method for hosts to discover neighbouring routers without any manual configuring or DHCP support.
The Solicitation (type 10) message is sent by a host to multicast address 224.0.0.2, to request any routers on the local segment to identify themselves. Any routers that receive this message (and support IRDP) will reply with the Advertisement (type 9) message to announce their IP address as available for routing. Routers may also send the Advertisement message unsolicited on occasion (as more of an advertisement than a response).
If more than one router on the local segment responds, the host will pick the first response. If the host makes a poor choice, ICMP redirects will be used to make routing more efficient.
Code | Description |
---|---|
0 | Normal router advertisement |
16 | Does not route common traffic |
Time Exceeded
The time exceeded message can be generated for two different errors; One is that the TTL (Time To Live) field value in the IP header has decremented to zero, and the packet had to be dropped. The other is that a device could not reassemble a fragmented packed in the allocated time, and the packet was dropped. The code field is used to determine which one of these errors has been raised.
Code | Description |
---|---|
0 | Time to live exceeded in transit |
1 | Fragment reassembly time exceeded |
When a packet is sent from a source host, the TTL value in the IP header is set. Each layer-3 hop in the network will decrement this value by 1, and eventually the packet will either be delivered, or the TTL will drop to zero, and the packet will be discarded. This is done for loop prevention, so a packet will be dropped if it loops around for too long. When a router decrements the TTL to zero, it creates the Time Exceeded message, and sends it to the source host. Of course, this can be caused if the TTL is set too low in the first place.
This feature can be useful for security in some cases. For example, the BGP TTL Security feature will set the TTL so only routers within a maximum distance can be reached.
Be aware that some security devices, even though they are layer-3, do not decrement the TTL of packets passing through them.
The packet capture below shows an example of the Time Exceeded message, due to the TTL expiring.
There are times that a packet has to be fragmented into smaller pieces. When the fragments arrive at the destination, they need to be reassembled into the original packet. The occasional problem here is that one of the fragments may go missing, resulting in the entire packet being discarded.
To handle this, the IP stack starts a timer when the first fragment arrives. If the timer expires before all the fragments are reassembled, the packet is discarded, and the Time Exceeded message is created and sent to the source.
Parameter Problem
The Parameter Problem message is a generic ‘catch-all’ message. that is used if no more specific error applies. This will also be used if there is a corruption or missing data in the IP header.
When the Parameter Problem message is sent, a pointer is included in the high 8-bits of the second part of the header. This pointer contains the location of the problem in the original packet.
In some cases, the pointer is not included. For example, if there is data missing (codes 1 and 2), there will be no pointer. After all, it’s difficult to point to data that is not there.
Code | Description | Notes |
---|---|---|
0 | Pointer indicates the error | Location of the error in the packet |
1 | Missing a required option | An option is missing from the IP header |
2 | Bad length | The length is incorrect, suggesting that the packet is missing data |
Timestamp-Request and Timestamp-Reply
Timestamps can be used to synchronise time between devices. To achieve this, a device sends a Type 13 Timestamp-Request to another device. In the request, it includes the time that the packet was sent, measured in milliseconds past midnight in Universal time. The second four bytes of the header include an identifier and sequence number which are used to match requests and replies.
In response, the recipient generates a type 14 Timestamp-Reply. The header format is the same as the request, but the payload includes the original timestamp, the timestamp when the packet was received, and the timestamp for when the reply packet was sent.
Photuris
Photuris is an application-layer session-key management protocol (RFC2522). It is used to generate session keys and establish IPSec SA’s. It uses ICMP to report on negotiation failures.
Code | Description |
---|---|
0 | Bad SPI |
1 | Authentication Failed |
2 | Decompression failed |
3 | Decryption failed |
4 | Need Authentication |
5 | Need Authorization |
References
Wikipedia – Ping (networking utility)
Firewall.cx – ICMP – ECHO / ECHO REPLY (PING) MESSAGE
Wikipedia – ICMP Router Discovery Protocol
Network Sorcery – ICMP type 10, Router solicitation
INACON – Photuris
The TCP/IP Guide – ICMP Version 4 (ICMPv4) Error Message Types and Formats
ICMP (Internet Control Message Protocol — межсетевой протокол управляющих сообщений). ICMP является протоколом контрольных сообщений Структура межсетевого протокола IPv4. Протокол ICMP используется устройствами сети для отправки управляющих сообщений и сообщений об ошибках на компьютеры и серверы. Существует несколько областей применения протокола ICMP, например, объявление об ошибках в сети, объявление о перегрузке сети и устранение неполадок.
Каждое сообщение протокола ICMP передается по сети внутри пакета IP. Пакеты IP с сообщениями ICMP маршрутизируются точно так же, как и любые другие пакеты, без приоритетов, поэтому они также могут теряться. Мало того, при большой загруженности сети они могут вызывать дополнительную загрузку маршрутизаторов. Для того, чтобы не вызывать лавины сообщения об ошибках, предусмотрели, что в случае потери пакетов IP, которые сами «несут» сообщения ICMP об ошибках, новые сообщения ICMP об ошибке рождаться не будут.
ICMP только сообщает о возникших ошибках отправителю пакета; отправитель сам должен связать ошибки с конкретными прикладными программами и предпринять действия по исправлению ошибок.
Надо отметить, что большая часть ошибок исходит от отправителя, но другие — нет. Так как ICMP сообщает об ошибках отправителю, он не может использоваться, чтобы информировать промежуточные маршрутизаторы об ошибках. Например, пакет следует по пути через маршрутизаторы М1,М2,…,Мk. Если Мk содержит некорректную информацию о маршрутах и ошибочно отправит пакет на маршрутизатор Ме, то маршрутизатор Мe может лишь сообщить об ошибке отправителю пакета. К сожалению, отправитель не отвечает за эту проблему и не может управлять некорректно ведущим себя маршрутизатором Мk. Фактически, отправитель не сможет даже определить, какой маршрутизатор вызвал эту проблему.
Почему ограничивают протокол ICMP взаимодействием только с отправителем? Потому что IP- пакет содержит поля, которые определяют только отправителя и получателя; он не содержит полного описания своего пути через сеть (кроме необычных случаев, о которых мы скажем позже).
Если маршрутизатор обнаруживает ошибку, он просто не может узнать, какие промежуточные машины обрабатывали этот пакет, и поэтому не может сообщить им об ошибке. Вместо простого удаления пакета этот маршрутизатор использует протокол ICMP, чтобы сообщить отправителю о возникшей проблеме, надеясь на то, что администратор сети затем локализует и исправит ошибку.
Расшифровка кодов ICMP сообщений:
Ответ на некоторые ICMP-сообщения может привести к разглашению некоторой информации о хосте, в то время как другие — привести к модификации таблицы маршрутизации, поэтому их необходимо запретить.
Обычно выход во внешний мир разрешают ICMP-сообщениям 3, 8, 12, в то время как на вход принимают только 0, 3, 4, 11, 12.
Разрешение ICMP в Packet Filter Firewall (PF) (обновление 2018.08).
-
Пример
# Разрешить входящие ICMP ping пакеты. Остальные ICMP относятся к # TCP/UDP и разрешаются их статами. # pass in on $ext_if inet proto icmp to ($ext_if) icmp-type echoreq code 0
-
Пример
# ICMP Echo pass in log quick inet proto icmp from any to $AllIFs \ icmp-type 8 keep state
${fwcmd} add 00300 allow icmp from any to внешний_IP in via внешний_интерфейс icmptype 0,3,4,11,12 ${fwcmd} add 00301 allow icmp from внешний_IP to any out via внешний_интерфейс icmptype 3,8,12 ${fwcmd} add 00304 allow icmp from внешний_IP to any out via внешний_интерфейс frag ${fwcmd} add 00305 deny log icmp from any to any in via внешний_интерфейс
Правила для Правила iptables. Список возможных типов выводится по команде
# iptables -p icmp -h Valid ICMP Types: any echo-reply (pong) destination-unreachable network-unreachable host-unreachable protocol-unreachable port-unreachable fragmentation-needed source-route-failed network-unknown host-unknown network-prohibited host-prohibited TOS-network-unreachable TOS-host-unreachable communication-prohibited host-precedence-violation precedence-cutoff source-quench redirect network-redirect host-redirect TOS-network-redirect TOS-host-redirect echo-request (ping) router-advertisement router-solicitation time-exceeded (ttl-exceeded) ttl-zero-during-transit ttl-zero-during-reassembly parameter-problem ip-header-bad required-option-missing timestamp-request timestamp-reply address-mask-request address-mask-reply
Можно указать стандартный числовой код или сообщение. Пропустить все входящие ICMP-эхо-запросы (пинги).
# iptables -I INPUT -p icmp --icmp-type 8 -j ACCEPT # iptables -I INPUT -p icmp --icmp-type echo-request -j ACCEPT
Блокирует фрагменты ICMP-пакетов
iptables -I INPUT -p icmp -f -j DROP
Рекомендуемые правила для ICMP:
#!/bin/sh IPT="/sbin/iptables" $IPT -A INPUT -p icmp --icmp-type 3 -j ACCEPT # destination-unreachable 3/4 $IPT -A INPUT -p icmp --icmp-type 8 -j ACCEPT # echo request $IPT -A INPUT -p icmp --icmp-type 12 -j ACCEPT # IP header bad $IPT -A OUTPUT -p icmp --icmp-type 0 -j ACCEPT # $IPT -A OUTPUT -p icmp --icmp-type 3 -j ACCEPT # $IPT -A OUTPUT -p icmp --icmp-type 4 -j ACCEPT # $IPT -A OUTPUT -p icmp --icmp-type 11 -j ACCEPT # $IPT -A OUTPUT -p icmp --icmp-type 12 -j ACCEPT #
В отличие от цели DROP, где пакет просто отбрасывается, в данном случае отправителю будет отправлено IСМР-сообщение «Port unreachable / icmp port unreachable» («Порт недоступен»). С помощью опции –reject-with можно изменить тип ICMP-сообщения:
# iptables -A INPUT -s 1.2.3.4 -j REJECT --reject-with icmp-net-unreachable
У опции –reject-with есть следующие аргументы:
icmp-net-unreachable — сеть недоступна; icmp-host-unreachable — узел недоступен; icmp-port-unreachable — порт недоступен; icmp-proto-unreahable — неподдерживаемый протокол; icmp-net-prohibited — сеть запрещена; icmp-host-prohibited — узел запрещен.
По умолчанию будет передано сообщение port-unreachable.
Вышеперечисленные аргументы являются ICMP error messages.В дополнение к опции –reject-with TCP-пакеты можно отклонить с помощью аргумента tcp-reset, который отправляет RST-сообщения отправителю. Это наилучший с точки зрения безопасности способ, нужно обязательно использовать именно его. TCP RST пакеты используются для закрытия TCP соединений.
This tutorial explains ICMP error messages and their formats in detail. Learn what the ICMP error messages are, how they are formatted, and how they work.
For error reporting and controlling, IP protocol uses ICMP. ICMP is a collection of predefined messages that an IP enabled device can use to inform another device about a specific condition. For example, whenever a router fails to forward or deliver an IP packet, it sends an ICMP message back to the source that explains why it can’t forward or deliver the packet.
ICMP messages are divided into two categories: ICMP error messages and ICMP query or information messages. In this tutorial, we will discuss ICMP error messages.
ICMP error message format
Every ICMP error message describes a separate error message and requires an individual solution. However, all ICMP error messages use the same error message format to report the error.
The following image shows the basic structure and fields in the ICMP error message format.
The following table lists fields of ICMP error messages and provides a brief description of each field.
Field | Size (in bytes) | Description |
Message type | 1 | Indicate the specific ICMP error message or the group of messages. |
Message code | 1 | Indicate the particular message in the group if the message type represents the group. |
Checksum | 2 | Validate the ICMP message. |
Original Headers | 20 — 60 | Contain the full header of the failed IP packet. |
Original Data | 8 | Contain the first 64 bits of the failed IP packet. |
Without including the header and data of the failed IP packet, the length of an ICMP error message is eight bytes. After including these fields, the total length of an ICMP packet can be anywhere from 36 to 72 bytes.
The type and code fields
ICMP messages are organized in types and codes. Types and codes are numeric values. Every message type represents a single message or a group of messages. If a type represents a group of messages, then code values are used. Every code value represents a message in the group.
To view a complete list of all ICMP message types and codes, check the previous part of this article.
Both the type and code fields are used to specify the exact ICMP error message being sent. Both fields are 8 bits in length.
The checksum field
The checksum field is used to validate ICMP messages. The sending system sets the value of the checksum field to 0 and performs a simple checksum operation. After running the checksum operation, the sending system puts the calculated checksum value in the checksum field.
The receiving system reverses this procedure before processing the message. It sets the value checksum field to 0 and performs the same checksum operation. After running the checksum operation, it compares the result with the value stored in the checksum field. If both values are the same, the message is considered valid. All valid messages are processed while are invalid messages are discarded.
Message body
Every IP packet consists of two fields: header and data. IP protocol includes all necessary information in every IP packet making it capable to reach its destination by taking whatever path is available. This information is included in the header field of IP packets. The first 64 bits of the data field contain the header of the upper layer. It contains the source and destination port number field used by the TCP layer.
ICMP uses this information to inform the sender which IP packet failed. The message body field of an ICMP error message contains two fields: the original message header and the original message data. These fields are used to include the header and the first 64 bits of the data field of the failed message. When a source receives an ICMP error message, by examining the message body field it can determine which IP packet was failed.
ICMP Error messages
ICMP error messages are used to report non-transient delivery problems. ICMP provides two sets of error messages: one for IPv4 and another for IPv6. The following table lists all ICMP error messages.
ICMP message type | Description | Codes | IP Version |
3 | Destination Unreachable | 0 — 15 | IPv4 |
5 | Redirect | 0 — 3 | IPv4 |
11 | Time Exceeded | 0 — 1 | IPv4 |
12 | Parameter Problem | 0 -2 | IPv4 |
4 | Source Quench (Deprecated) | NA | IPv4 |
1 | Destination Unreachable | 0 — 8 | IPv6 |
2 | Packet Too Big | 0 | IPv6 |
3 | Time Exceeded | 0 — 1 | IPv6 |
4 | Parameter Problem | 0 — 10 | IPv6 |
Let’s discuss ICMP error messages in detail.
Destination unreachable
This error message indicates that the destination host, network, or port number that is specified in the IP packet is unreachable. This could happen due to a lot of reasons such as the destination host device is down, an intermediate router is unable to find a path to forward the packet, and a firewall is configured to block connections from the source of the packet.
As mentioned earlier, if there are multiple reasons for a particular error, ICMP defines them in the subclass or category of that error message. Messages in the sub-category are called codes. ICMP defines 16 possible codes for IPv4 for this error message. From these, three are obsolete or inappropriate for normal usages.
The following table lists all codes for the IPv4 destination unreachable error message.
Code | Description |
0 | Net Unreachable |
1 | Host Unreachable |
2 | Protocol Unreachable |
3 | Port Unreachable |
4 | Fragmentation Needed and Don’t Fragment was Set |
5 | Source Route Failed |
6 | Destination Network Unknown |
7 | Destination Host Unknown |
8 | Source Host Isolated (obsolete) |
9 | Communication with Destination Network is Administratively Prohibited (obsolete) |
10 | Communication with Destination Host is Administratively Prohibited (obsolete) |
11 | Destination Network Unreachable for Type of Service |
12 | Destination Host Unreachable for Type of Service |
13 | Communication Administratively Prohibited |
14 | Host Precedence Violation |
15 | Precedence cutoff in effect |
For IPv6, IPCMP defines nine codes. These codes are listed in the following table.
Code | Description |
0 | no route to the destination |
1 | communication with destination administratively prohibited |
2 | beyond scope of source address |
3 | address unreachable |
4 | port unreachable |
5 | source address failed ingress/egress policy |
6 | reject route to the destination |
7 | Error in Source Routing Header |
8 | Headers too long |
Source Quench
This message indicates that either the destination host or an intermediary router (or device) is receiving more data than it can process. If a source receives this error message, it can reduce the rate of transfer to solve this issue.
This error mostly occurs when a router connects a high bandwidth network (such as LAN) to a low-bandwidth network (such as dial-up). In such a situation, a sender device may transmit more data than a device working in the low-bandwidth network can feed.
This error message type has been depreciated.
Redirect
This error message is used when a router needs to tell a sender that it should use a different path for a particular destination. Usually, it happens when the router knows a shorter path to the destination.
This error message has four sub-types. From them, two have been depreciated. The following lists all sub-types and their meanings.
Code | Meaning |
0 | Redirect for Destination Network (deprecated) |
1 | Redirect for Destination Host |
2 | Redirect for Destination Network Based on Type-of-Service (deprecated) |
3 | Redirect for Destination Host Based on Type-of-Service |
Time Exceeded
This message indicates that the Time-To-Live value of the datagram has reached zero but the datagram has not yet been reached the final destination. A destination system can also send this error when it does not receive all fragments on an IP datagram within the allotted time.
There are two sub-types of this error message. Both are listed in the following table.
Code | Meaning |
0 | Time-to-Live Exceeded in Transit |
1 | Fragment Reassembly Time Exceeded |
Parameter Problem
If a device finds a problem that is not covered in any ICMP message type, it sends a parameter problem message to the sender. In IPv4 network, usually it occurs when arguments to an option are incorrect. In IPv6, this error occurs when the value in the header field is out of the range, or one of the options is not recognized, or the value in the type or code field is invalid.
Most of the time this problem belongs to problems with IP or TCP Options. The following table lists ICMP code messages that belong to this error.
Code | Description | IP version |
0 | Pointer indicates the error | IPv4 |
1 | Missing a Required Option | IPv4 |
2 | Bad Length | IPv4 |
0 | erroneous header field encountered | IPv6 |
1 | unrecognized Next Header type encountered | IPv6 |
2 | unrecognized IPv6 option encountered | IPv6 |
3 | IPv6 First Fragment has incomplete IPv6 Header Chain | IPv6 |
4 | SR Upper-layer Header Error | IPv6 |
5 | Unrecognized Next Header type encountered by an intermediate node | IPv6 |
6 | Extension header too big | IPv6 |
7 | Extension header chain too long | IPv6 |
8 | Too many extension headers | IPv6 |
9 | Too many options in the extension header | IPv6 |
10 | Option too big | IPv6 |
Packet too big
This error occurs when a datagram is too big for a network over which it must travel. To report this problem, ICMP uses different message types and codes in both versions of IP. In IPv4, it uses a destination unreachable message with the code field set to 4. In IPv6, it uses a packet too big message which has a type field of 2.
The maximum size of a datagram that can be transmitted over a network is measured in MTU. To transmit data successfully, a source must discover MTU. MTU discovery involves receiving information about the MTU of remote networks.
This message contains a field that allows routers to inform the source about the MTU of the network that caused the problem. Once the source knows the MTU that failed its datagram, it can adjust MTU accordingly.
That’s all for this tutorial. In this tutorial, we discussed the ICMP error messages and their format. If you like this tutorial, please don’t forget to share it with friends through your favorite social channel.
By ComputerNetworkingNotes
Updated on 2023-08-29 07:00:01 IST
Аннотация: Описан протокол ICMP и его приложения, контроль доступности и управление перегрузкой, типы и коды ICMP, протокол управления перегрузкой для дейтаграмм DCCP
Протокол передачи команд и сообщений об ошибках ( ICMP — internet control message protocol, RFC-792, — 1256) выполняет различные и не только диагностические функции. При пересылке пакетов промежуточные узлы не информируются о возникших проблемах, поэтому ошибка в маршрутной таблице может восприниматься как неисправность в узле адресата и достоверно диагностироваться не будет. ICMP-протокол сообщает об ошибках в IP-дейтаграммах, но не дает информации об ошибках в самих ICMP-сообщениях. ICMP использует IP, а IP-протокол должен использовать ICMP. В случае ICMP-фрагментации сообщение об ошибке будет выдано только один раз на дейтаграмму, даже если ошибки были в нескольких фрагментах. Подводя итоги, можно сказать, что ICMP-протокол:
- осуществляет передачу запросов и откликов;
- контролирует время жизни дейтаграмм в системе;
- реализует переадресацию пакета;
- выдает сообщения о недостижимости адресата или о некорректности параметров;
- формирует и пересылает временные метки;
- выдает запросы и отклики для адресных масок и другую информацию.
ICMP-сообщения об ошибках никогда не выдаются:
- в ответ на ICMP-сообщение об ошибке;
- при мультикастинг-е или широковещательной адресации;
- для фрагмента дейтаграммы (кроме первого);
- для дейтаграмм, чей адрес отправителя является нулевым, широковещательным или мультикастинговым.
Эти правила призваны блокировать потоки дейтаграмм, посылаемые в отклик на мультикастинг- или широковещательные ICMP-сообщения. Особенности протокола ICMPv6 описаны в документе RFC-2463. В IPv6 на протокол ICMP возложены функции управления группами (IGMP).
ICMP-сообщения имеют свой формат, а схема их вложения аналогична UDP или TCP и представлена на рис. 3.1.
Все ICMP пакеты начинаются с 8-битного поля типа ICMP и его кода (15 значений).
Рис.
3.1.
Схема вложения ICMP-пакетов в Ethernet-кадр
По существу, значения полей типа и кода выполняют почти ту же функцию, что и порт в ТСР и UDP-протоколах.
Код уточняет функцию ICMP-сообщения. Таблица 3.1 этих кодов приведена ниже (символом * помечены сообщения об ошибках, остальные являются запросами).
Процедура «отключение источника» (quench, поле тип ICMP=4 ) позволяет управлять потоками данных в каналах Интернет. Не справляясь с обработкой дейтаграмм, ЭВМадресат (или транзитное сетевое устройство) может послать запрос «отключить источник» отправителю, который может сократить темп посылки пакетов, например, вдвое, или вовсе прервать их посылку. Специальной команды, отменяющей прежние запреты, не существует. Если сообщения об отключении прекращаются, источник может возобновить посылку пакетов или увеличить частоту их отправки. Ниже (на рис. 3.2) представлен формат эхозапроса (ping) и отклика для протокола ICMP.
Поля идентификатор (обычно это идентификатор процесса) и номер по порядку (увеличивается на 1 при посылке каждого пакета) служат для того, чтобы отправитель мог связать в пары запросы и отклики.
Поле тип определяет, является ли этот пакет запросом (8) или откликом (0). Поле контрольная сумма представляет собой 16-разрядное дополнение по модулю 1 контрольной суммы всего ICMP-сообщения, начиная с поля тип. Поле данные служит для записи информации, возвращаемой отправителю. При выполнении процедуры ping эхозапрос с временной меткой в поле данные посылается адресату. Если адресат активен, он принимает IP-пакет, меняет адрес отправителя и получателя местами и посылает его обратно. ЭВМ-отправитель, восприняв этот отклик, может сравнить временную метку, записанную им в пакет, с текущим показанием внутренних часов и определить время распространения пакета (RTT — round trip time). Размер поля данные не регламентирован и определяется предельным размером IP-пакета.
ICMP-сообщение | описание сообщения | |
---|---|---|
Тип | код | |
0 | Эхо-ответ (ping-отклик) | |
3 | Адресат недостижим | |
0 | * Сеть недостижима | |
1 | * ЭВМ недостижима | |
2 | * Протокол недоступен | |
3 | * Порт недоступен | |
4 | * Необходима фрагментация сообщения (установлен флаг DF) | |
5 | * Маршрутизация отправителя нереализуема | |
6 | * Сеть места назначения неизвестна | |
7 | * ЭВМ места назначения неизвестна | |
8 | * Исходная ЭВМ изолирована (устарело) | |
9 | * Связь с сетью места назначения административно запрещена | |
10 | * Связь с ЭВМ места назначения административно запрещена | |
11 | * Сеть не доступна для данного вида сервиса (TOS) | |
12 | * ЭВМ не доступна для данного вида сервиса (TOS) | |
13 | * Связь административно запрещена с помощью фильтра | |
14 | * Нарушение старшинства ЭВМ | |
15 | * Дискриминация по старшинству | |
4 | 0 | * Отключение источника при переполнении очереди (quench) |
5 | Переадресовать (изменить маршрут) | |
0 | Переадресовать дейтаграмму в сеть (устарело) | |
1 | Переадресовать дейтаграмму на ЭВМ | |
2 | Переадресовать дейтаграмму для типа сервиса (ToS) и сети | |
3 | Переадресовать дейтаграмму для типа сервиса и ЭВМ | |
8 | 0 | Эхо запроса (ping-запрос) |
9 | 0 | Объявление маршрутизатора |
10 | 0 | Запрос маршрутизатора |
11 | Для дейтаграммы время жизни истекло (ttl=0): | |
0 | *при передаче | |
1 | * тайм-аут при сборке (случай фрагментации) | |
12 | * Проблема с параметрами дейтаграммы | |
0 | * Ошибка в IP-заголовке | |
1 | * Отсутствует необходимая опция | |
13 | Запрос временной метки | |
14 | Временная метка-отклик | |
15 | Запрос информации (устарел) | |
16 | Информационный отклик (устарел) | |
17 | Запрос адресной маски | |
18 | Отклик на запрос адресной маски |
Рис.
3.2.
Формат эхо-запроса и отклика ICMP
Рис.
3.2a.
Так как в пакете ICMP нет поля порт, то при запуске нескольких процессов PING одновременно может возникнуть проблема с тем, какому из процессов следует передать тот или иной отклик. Для преодоления этой неопределенности следует использовать уникальные значения полей идентификатор.
Время распространения ICMP-запроса, вообще говоря, не равно времени распространения отклика (ситуация с очередями, например, в маршрутизаторах может быть разной). Это связано не только с возможными изменениями в канале. В общем случае маршруты их движения могут быть различными. Те же запросы используются при выполнении процедуры Traceroute.
Эта процедура позволяет не только диагностировать, но и оптимизировать маршрут. Например, команда traceroute cernvm.cern.ch, выданная в ЭВМ SUN (ИТЭФ), может отобразить на экране (в скобках указаны IP-адреса узлов и значения времени жизни дейтаграмм, значения RTT приводится в миллисекундах) (таблица 3.1.1.):
traceroute to crnvma cern ch | (128 141 2 4) 30 hops max, 40 byte packets | |
---|---|---|
1 | itep-fddi-bbone | (193.124.224.50) 3 ms 2 ms 3 ms |
2 | msu—tower.moscow.ru.radio-msu.net | (193.124.137.13) 3 ms 3 ms 3 ms |
3 | npi-msu.moscow.ru.radio-msu.net | (193.124.137.9) 27 ms 3 ms 9 ms |
4 | desy.hamburg.de.radio-msu.net | (193.124.137.6) 556 ms 535 ms 535 ms |
5 | * 188.1.133.56 | (188.1.133.56) 637ms 670ms |
6 | duesseldorf2.empb.net | (193.172.4.12) 740ms(ttl=59!) 839ms(ttl=59!) 2066ms(ttl=59!) |
7 | bern3.empb.net | (193.172.4.30) 2135ms (ttl=58!) 1644ms (ttl=58!) 1409ms (ttl=58!) |
8 | cernh3.euro-hep.net | (193.172.24.10) 1808ms 1508ms 1830ms |
9 | cgate1.cern.ch | (192.65.185.1) 1116ms 1270ms 1278ms |
10 | crnvma.cern.ch | (128.141.2.4) 1132ms 1362ms 1524ms |
Отсюда видно, что наиболее узкими участками маршрута (на момент выполнения процедуры) являются Гамбург-Дюссельдорф-Берн-CERN. Следует иметь в виду, что канал МГУ-Гамбург был спутниковым и 500мс задержки здесь вносит удвоенное время распространения сигнала до спутника и обратно. Участок Гамбург-Дюссельдорф (X.25, квота 256кбит/с) был общим для потока данных из Германии в США. Передача IP поверх X.25 также снижает эффективную широкополосность канала. Остальные связи обладают недостаточной пропускной способностью. Программа ping показывает для данных участков в часы пик высокую долю потерянных пакетов. Таким образом, имея карту связей и используя указанные процедуры, вы можете успешно диагностировать ситуацию в сети. Продвинутые же программисты могут легко написать свои диагностические программы, базирующиеся на ICMP, как для локальной сети, так и для «окрестного» Интернет.
Когда маршрутизатор не может доставить дейтаграмму по месту назначения, он посылает отправителю сообщение «адресат недостижим» (destination unreachable). Формат такого сообщения показан ниже (на рис. 3.3).
Рис.
3.3.
Формат ICMP-сообщения «адресат недостижим»
Поле код содержит целое число, проясняющее положение дел. Перечень кодов таких сообщений помещен в таблице 3.1. Поле MTU на следующем этапе характеризует максимальную длину пакетов на очередном шаге пересылки. Эта информация (MTU) позволяет выбрать оптимальный размер пакета.
Так как в сообщении содержится Интернет-заголовок и первые 64-бита дейтаграммы, легко понять, какой адрес оказался недостижим. Этот тип ICMP-сообщения посылается и в случае, когда дейтаграмма имеет флаг DF=1 («не фрагментировать»), а фрагментация необходима. В поле код в этом случае будет записано число 4.
Если буфер приема сообщения переполнен, ЭВМ посылает сообщение типа 4.
Так как собственные часы различных ЭВМ имеют свое представление о времени, протокол ICMP, среди прочего, служит для синхронизации работы различных узлов, если это требуется (запросы временных меток). Протокол синхронизации NTP (network time protocol) описан в RFC-1119.
Когда дейтаграммы поступают слишком часто и принимающая сторона не справляется с этим потоком, отправителю может быть послано сообщение с требованием резко сократить информационный поток (quenchзапрос). Снижение потока должно продолжаться до тех пор, пока не прекратятся quenchзапросы. Такое сообщение имеет формат, показанный на рис. 3.4.
Рис.
3.4.
Формат ICMP-запроса снижения загрузки
В Internet таблицы маршрутизации остаются без изменений достаточно долгое время, но иногда они все же меняются. Если маршрутизатор обнаружит, что ЭВМ использует неоптимальный маршрут, он может послать ей ICMP—запрос переадресации. При этом следует учитывать, что этой возможностью может воспользоваться и хакер. Формат такого сообщения отображен на рисунке 3.5.
Рис.
3.5.
Формат ICMP-запроса переадресации
Поле Internet-адрес маршрутизатора содержит адрес маршрутизатора, который ЭВМ должна использовать, чтобы посланная дейтаграмма достигла места назначения, указанного в ее заголовке. В поле internet-заголовок кроме самого заголовка лежит 64 первых бита дейтаграммы, вызвавшей это сообщение. Поле код специфицирует то, как нужно интерпретировать адрес места назначения (см. табл. 3.1).
Команды переадресации маршрутизатор посылает только ЭВМ и никогда другим маршрутизаторам. Рассмотрим конкретный пример. Пусть некоторая ЭВМ на основе своей маршрутной таблицы посылает пакет маршрутизатору M1. Он, просмотрев свою маршрутную таблицу, находит, что пакет следует переслать маршрутизатору M2. Причем выясняется, что пакет из M1 в M2 следует послать через тот же интерфейс, через который он попал в M1. Это означает, что M2 доступен и непосредственно для ЭВМ-отправителя. В такой ситуации M1 посылает ICMP—запрос переадресации ЭВМ-отправителю указанного пакета с тем, чтобы она внесла соответствующие коррективы в свою маршрутную таблицу (либо чтобы администратор поменял IPадрес или маску ЭВМ).
Маршрутная таблица может загружаться из файла, формироваться менеджером сети, но может создаваться и в результате запросов и объявлений, посылаемых маршрутизаторами. После загрузки системы маршрутизатор посылает широковещательный запрос. Один или более маршрутизаторов посылают в ответ сообщения об имеющейся маршрутной информации. Кроме того, маршрутизаторы периодически (раз в 450600 сек.) широковещательно объявляют о своих маршрутах, что позволяет другим маршрутизаторам скорректировать свои маршрутные таблицы. В RFC-1256 описаны форматы ICMP-сообщений такого рода (см. рис. 3.6). Из—за своей уязвимости данная технология в последнее время практически не используется.
Рис.
3.6.
Формат ICMP-сообщений об имеющихся маршрутах
Поле число адресов характеризует количество адресных записей в сообщении. Поле длина адреса содержит число 32-битных слов, необходимых для описания адреса маршрутизатора. Поле время жизни предназначено для записи продолжительности жизни объявленных маршрутов (адресов) в секундах. По умолчанию время жизни равно 30 мин. Поля уровень приоритета представляют собой меру приоритетности маршрута по отношению к другим маршрутам данной подсети. Чем больше этот код, тем выше приоритет. Маршрут по умолчанию имеет уровень приоритета 0. Формат запроса маршрутной информации (8 октетов, рис. 3.7).
Рис.
3.7.
Формат запроса маршрутной информации
Если вы работаете с ОС Windows, а конфигурационными сетевыми параметрами являются IP—адрес вашей ЭВМ, сетевая маска и адреса GW и DNS, то процедуры переадресации, скорее всего к вам отношения не имеют.
Так как следующий прогон (hop) дейтаграммы определяется на основании локальной маршрутной таблицы, ошибки в последней могут привести к зацикливанию пакетов. Причиной зацикливания могут быть и многие другие причины. Для подавления таких циркуляций используется контроль по времени жизни пакета (TTL). При ликвидации пакета по истечении TTL маршрутизатор посылает отправителю сообщение «время истекло», которое имеет формат (рис. 3.8):
Рис.
3.8.
Формат сообщения «время (TTL) истекло»
Значение поля код определяет природу таймаута (см. табл. 3.1).
Когда маршрутизатор или ЭВМ выявили какую-либо ошибку, не из числа описанных выше (например, нелегальный заголовок дейтаграммы), посылается сообщение «конфликт параметров». Это может произойти, например, при неверных параметрах опций. В этом случае посылается сообщение вида (рис. 3.9):
Рис.
3.9.
Формат сообщения типа «конфликт параметров»
Поле указатель отмечает октет дейтаграммы, который создал проблему. Код=1 применяется для сообщения о том, что отсутствует требуемая опция (например, опция безопасности при конфиденциальных обменах); поле указатель при значении поля код=1 не используется.
В процессе трассировки маршрутов возникает проблема синхронизации работы часов в различных ЭВМ. К счастью, синхронизация внутренних часов ЭВМ требуется не так часто (например, при выполнении синхронных измерений), негативную роль здесь могут играть задержки в каналах связи. Для запроса временной метки другой ЭВМ используется сообщение запрос временной метки, которое вызывает отклик с форматом (рис. 3.10):
Рис.
3.10.
Формат ICMP-запроса временной метки
Поле тип=13 указывает на то, что это запрос, а тип=14 — на то, что это отклик. Поле идентификатор и номер по порядку используются отправителем для связи запроса и отклика. Поле исходная временная метка заполняется отправителем непосредственно перед отправкой пакета. Поле временная метка на входе заполняется маршрутизатором при получении этого пакета, а временная метка на выходе — непосредственно перед его отправкой.
При работе с субсетью важно знать маску этой субсети. Как уже отмечалось выше, IPадрес содержит секцию адреса ЭВМ и секцию адреса сети. Для получения маски субсети ЭВМ может послать «запрос маски» в маршрутизатор и получить отклик, содержащий эту маску. ЭВМ может это сделать непосредственно, если ей известен адрес маршрутизатора, либо прибегнуть к широковещательному запросу. Ниже описан формат таких запросовоткликов (рис. 3.11).
Рис.
3.11.
Формат запроса (отклика) маски субсети
Поле тип здесь специфицирует модификацию сообщения, тип=17 — это запрос, а тип=18 — отклик. Поля идентификатор и номер по порядку, как обычно, обеспечивают взаимную привязку запроса и отклика, а поле адресная маска содержит 32-разрядную маску сети.
Процесс интеграции услуг в Интернет несколько лет назад перешел в практическую плоскость и вслед за IPтелефонией, настала очередь цифрового телевидения. Главным транспортным средством для мультимедиа-данных является протокол UDP (RTP/RTCP). Но в протоколе UDP нет встроенных средств для подавления перегрузки. Возможность использования ICMP(4) трудно рассматривать всерьез, так как этот механизм достаточно груб и включается тогда, когда перегрузка уже привела к потере пакетов. Решить проблему управления перегрузкой в потоках без гарантии доставки должен новый протокол DCCP.