Chapter 8. ICMPv4 and ICMPv6: Internet Control Message Protocol
Introduction
The IP protocol alone provides no direct way to do the following:
- For an end system to learn the fate of IP packets that fail to make it to their destinations.
- For obtaining diagnostic information (e.g., which routers are used along a path or a method to estimate the round-trip time).
To address these deficiencies, a special protocol called the Internet Control Message Protocol (ICMP) is used in conjunction with IP to provide diagnostics and control information related to the configuration of the IP protocol layer and the disposition of IP packets.
ICMP provides for the delivery of error and control messages that may require attention. ICMP messages are usually acted on by:
- The IP layer itself,
- Higher-layer transport protocols (TCP or UDP),
- User applications.
ICMP does not provide reliability for IP; it indicates certain classes of failures and configuration information. The most common cause of packet drops (buffer overrun at a router) does not elicit any ICMP information. Other protocols, such as TCP, handle such situations.
Because of the ability of ICMP to affect the operation of important system functions and obtain configuration information, hackers have used ICMP messages in a large number of attacks. As a result of concerns about such attacks, network administrators often arrange to block ICMP messages with firewalls, especially at border routers. If ICMP is blocked, however, a number of common diagnostic utilities (e.g., ping, traceroute) do not work properly.
The term ICMP refers to ICMP in general, and the terms ICMPv4 and ICMPv6 to refer specifically to the versions of ICMP used with IPv4 and IPv6, respectively. ICMPv6 plays a far more important role in the operation of IPv6 than ICMPv4 does for IPv4.
In IPv6, ICMPv6 is used for several purposes beyond simple error reporting and signaling. It is used for:
- Neighbor Discovery (ND), which plays the same role as ARP does for IPv4 (Chapter 4).
- Router Discovery function used for configuring hosts (Chapter 6) and multicast address management (Chapter 9).
- Manageing hand-offs in Mobile IPv6.
Encapsulation in IPv4 and IPv6
- In IPv4, a Protocol field value of 1 indicates that the datagram caries ICMPv4.
- In IPv6, the ICMPv6 message may begin after zero or more extension headers. The last extension header before the ICMPv6 header includes a Next Header field with value 58.
ICMP messages may be fragmented like other IP datagrams (Chapter 10), although this is not common.
The following figure shows the format of both ICMPv4 and ICMPv6 messages. The first 4 bytes have the same format for all messages, but the remainder differ from one message to the next.
In ICMPv4:
- 42 different values are reserved for the Type field [ICMPTYPES], which identify the particular message. Only about 8 of these are in regular use.
- Many types of ICMP messages also use different values of the Code field to further specify the meaning of the message.
- The Checksum field covers the entire ICMPv4 message; in ICMPv6 it also covers a pseudo-header derived from portions of the IPv6 header. The algorithm used for computing the checksum is the same as that used for the IP header checksum defined in Chapter 5.
- This is our first example of an end-to-end checksum. It is carried all the way from the sender of the ICMP message to the final recipient. In contrast, the IPv4 header checksum discussed in Chapter 5 is changed at every router hop. If an ICMP implementation receives an ICMP message with a bad checksum, the message is discarded; there is no ICMP message to indicate a bad checksum in a received ICMP message. Recall that the IP layer has no protection on the payload portion of the datagram. If ICMP did not include a checksum, the contents of the ICMP message might not be correct, leading to incorrect system behavior.
ICMP Messages
ICMP messages are grouped into two major categories:
- Error messages: related to problems with delivering IP datagrams.
- Query or information messages: related to information gathering and configuration.
ICMPv4 Messages
For ICMPv4, the informational messages include:
- Echo Request (type
- Echo Reply (type 0)
- Router Advertisement (type 9)
- Router Solicitation (type 10)
Router Advertisement and Router Solicitation are together called Router Discovery.
The most common error message types are:
- Destination Unreachable (type 3)
- Redirect (type 5)
- Time Exceeded (type 11)
- Parameter Problem (type 12)
The table below lists the message types defined for standard ICMPv4 messages. Types marked with asterisks (*) are the most common. Those marked with a plus (+) may contain [RFC4884] extension objects. In the fourth column, E is for error messages and I indicates query/informational messages.
Type | Official Name | Reference | E/I | Use/Comment |
---|---|---|---|---|
0 (*) | Echo Reply | [RFC0792] | I | Echo (ping ) reply; returns data |
3 (*)(+) | Destination Unreachable | [RFC0792] | E | Unreachable host/protocol |
4 | Source Quench | [RFC0792] | E | Indicates congestion (deprecated) |
5 (*) | Redirect | [RFC0792] | E | Indicates alternate router should be used |
8 (*) | Echo | [RFC0792] | I | Echo (ping ) request (data optional) |
9 | Router Advertisement | [RFC1256] | I | Indicates router addresses/preferences |
10 | Router Solicitation | [RFC1256] | I | Requests Router Advertisement |
11 (*)(+) | Time Exceeded | [RFC0792] | E | Resource exhausted (e.g., IPv4 TTL) |
12 (*)(+) | Parameter Problem | [RFC0792] | E | Malformed packet or header |
For the commonly used messages, the code numbers shown in the table below are used. Some messages are capable of carrying extended information
Type | Code | Official Name | Use/Comment |
---|---|---|---|
3 | 0 | Net Unreachable | No route (at all) to destination |
3 (*) | 1 | Host Unreachable | Known but unreachable host |
3 | 2 | Protocol Unreachable | Unknown (transport) protocol |
3 (*) | 3 | Port Unreachable | Unknown/unused (transport) port |
3 (*) | 4 | Fragmentation Needed and Don’t Fragment Was Set (PTB message) | Needed fragmentation prohibited by DF bit; used by PMTUD [RFC1191] |
3 | 5 | Source Route Failed | Intermediary hop not reachable |
3 | 6 | Destination Network Unknown | Deprecated [RFC1812] |
3 | 7 | Destination Host Unknown | Destination does not exist |
3 | 8 | Source Host Isolated | Deprecated [RFC1812] |
3 | 9 | Communication with Destination Network Administratively | Prohibited Deprecated [RFC1812] |
3 | 10 | Communication with Destination Host Administratively | Prohibited Deprecated [RFC1812] |
3 | 11 | Destination Network Unreachable for Type of Service | Type of service not available (net) |
3 | 12 | Destination Host Unreachable for Type of Service | Type of service not available (host) |
3 | 13 | Communication Administratively Prohibited | Communication prohibited by filtering policy |
3 | 14 | Host Precedence Violation | Precedence disallowed for src/dest/port |
3 | 15 | Precedence Cutoff in Effect | Below minimum ToS [RFC1812] |
5 | 0 | Redirect Datagram for the Network (or Subnet) | Indicates alternate router |
5 (*) | 1 | Redirect Datagram for the Host | Indicates alternate router (host) |
5 | 2 | Redirect Datagram for the Type of Service and Network | Indicates alternate router (ToS/net) |
5 | 3 | Redirect Datagram for the Type of Service and Host | Indicates alternate router (ToS/host) |
9 | 0 | Normal Router Advertisement | Router’s address and configuration information |
9 | 16 | Does Not Route Common Traffic | With Mobile IP [RFC5944], router does not route ordinary packets |
11 (*) | 0 | Time to Live Exceeded in Transit | Hop limit/TTL exceeded |
11 | 1 | Fragment Reassembly Time Exceeded | Not all fragments of datagram arrived before reassembly timer expired |
12 (*) | 0 | Pointer Indicates the Error | Byte offset (pointer) indicates first problem field |
12 | 1 | Missing a Required Option | Deprecated/historic |
12 | 2 | Bad Length Packet had invalid | Total Length field |
ICMPv6 Messages
ICMPv6 is responsible not only for error and informational messages but also for a great deal of IPv6 router and host configuration.
[p358-359]
In ICMPv6, as in ICMPv4, messages are grouped into the informational and error classes. In ICMPv6, however, all the error messages have a 0 in the high-order bit of the Type field. Thus, ICMPv6 types 0 through 127 are all errors, and types 128 through 255 are all informational. Many of the informational messages are request/reply pairs.
In comparing the common ICMPv4 messages with the ICMPv6 standard messages, we conclude that some of the effort in designing ICMPv6 was to eliminate the unused messages from the original specification while retaining the useful ones. Following this approach, ICMPv6 also makes use of the Code field, primarily to refine the meanings of certain error messages.
[p360]
In addition to the Type and Code fields that define basic functions in ICMPv6, a large number of standard options are also supported, some of which are required. This distinguishes ICMPv6 from ICMPv4 (ICMPv4 does not have options).
Processing of ICMP Messages
In ICMP, the processing of incoming messages varies from system to system. Generally:
- Incoming informational requests are handled automatically by the operating system.
- Error messages are delivered to user processes or to a transport protocol such as TCP.
The processes may choose to act on them or ignore them. Exceptions to this general rule include:
- The Redirect message. This results in an automatic update to the host’s routing table.
- The Destination Unreachable—Fragmentation Required messages. This is used in the path MTU discovery (PMTUD) mechanism, which is generally implemented by the transport-layer protocols such as TCP.
In ICMPv6, the following rules are applied when processing incoming ICMPv6 messages:
- Unknown ICMPv6 error messages must be passed to the upper-layer process that produced the datagram causing the error (if possible).
- Unknown ICMPv6 informational messages are dropped.
- ICMPv6 error messages include as much of the original («offending») IPv6 datagram that caused the error as will fit without making the error message datagram exceed the minimum IPv6 MTU (1280 bytes).
- When processing ICMPv6 error messages, the upper-layer protocol type is extracted from the original or «offending» packet (contained in the body of the ICMPv6 error message) and used to select the appropriate upper-layer process. If this is not possible, the error message is silently dropped after any IPv6-layer processing.
- There are special rules for handling errors (see Section 8.3).
- An IPv6 node must limit the rate of ICMPv6 error messages it sends. There are a variety of ways of implementing the rate-limiting
ICMP Error Messages
The distinction between the error and informational classes of ICMP messages is important. An ICMP error message is not to be sent in response to any of the following messages:
- Another ICMP error message,
- Datagrams with bad headers (e.g., bad checksum),
- IP-layer broadcast/multicast datagrams,
- Datagrams encapsulated in link-layer broadcast or multicast frames,
- Datagrams with an invalid or network zero source address,
- Any fragment other than the first.
The reason for imposing these restrictions on the generation of ICMP errors is to limit the creation of so-called broadcast storms, a scenario in which the generation of a small number of messages creates an unwanted traffic cascade (e.g., by generating error responses in response to error responses, indefinitely). These rules can be summarized as follows:
ICMPv4 error messages *
An ICMPv4 error message is never generated in response to:
- An ICMPv4 error message. (An ICMPv4 error message may, however, be generated in response to an ICMPv4 query message.)
- A datagram destined for an IPv4 broadcast address or an IPv4 multicast address (formerly known as a class D address).
- A datagram sent as a link-layer broadcast.
- A fragment other than the first.
- A datagram whose source address does not define a single host. This means that the source address cannot be any of the following:
- Zero address,
- Loopback address,
- Broadcast address,
- Multicast address.
ICMPv4 error messages *
An ICMPv6 error message is never generated in response to
- An ICMPv6 error message
- An ICMPv6 Redirect message
- A packet destined for an IPv6 multicast address, with two exceptions:
- The Packet Too Big (PTB) message
- The Parameter Problem message (code 2)
- A packet sent as a link-layer multicast (with the exceptions noted previously)
- A packet sent as a link-layer broadcast (with the exceptions noted previously)
- A packet whose source address does not uniquely identify a single node. This means that the source address cannot be any of the following:
- Unspecified address,
- IPv6 multicast address,
- Any address known by the sender to be an anycast address.
Rate-limiting ICMP messages with token buckets *
In addition to the rules governing the conditions under which ICMP messages are generated, there is also a rule that limits the overall ICMP traffic level from a single sender. In [RFC4443], a recommendation for rate-limiting ICMP messages is to use a token bucket.
With a token bucket, a «bucket» holds a maximum number (B) of «tokens», each of which allows a certain number of messages to be sent. The bucket is periodically filled with new tokens (at rate N) and drained by 1 for each message sent. Thus, a token bucket (or token bucket filter, as it is often called) is characterized by the parameters (B, N). For small or midsize devices, [RFC4443] provides an example token bucket using the parameters (10, 10). Token buckets are a common mechanism used in protocol implementations to limit bandwidth utilization, and in many cases B and N are in byte units rather than message units.
Copy of offending datagram headers in ICMP error message
When an ICMP error message is sent, it contains a copy of the full IP header from the «offending» or «original» datagram (i.e., the IP header of the datagram that caused the error to be generated, including any IP options), plus any other data from the original datagram’s IP payload area such that the generated IP/ ICMP datagram’s size does not exceed a specific value. For IPv4 this value is 576 bytes, and for IPv6 it is the IPv6 minimum MTU, which is at least 1280 bytes.
Including a portion of the payload from the original IP datagram lets the receiving ICMP module associate the message with one particular protocol (e.g., TCP or UDP) from the Protocol or Next Header field in the IP header and one particular user process (from the TCP or UDP port numbers that are in the TCP or UDP header contained in the first 8 bytes of the IP datagram payload area).
[p362-363]
Extended ICMP and Multipart Messages
[p363-364]
Destination Unreachable (ICMPv4 Type 3, ICMPv6 Type 1) and Packet Too Big (ICMPv6 Type 2)
Messages of this type are used to indicate that a datagram could not be delivered all the way to its destination because of either a problem in transit or the lack of a receiver interested in receiving it. Although 16 different codes are defined for this message in ICMPv4, only 4 are commonly used. These include:
- Host Unreachable (code 1)
- Port Unreachable (code 3)
- Fragmentation Required/ Don’t-Fragment Specified (code 4),
- Communication Administratively Prohibited (code 13).
In ICMPv6, the Destination Unreachable message is type 1 with seven possible code values. In ICMPv6, as compared with IPv4, the Fragmentation Required message has been replaced by an entirely different type (type 2), but the usage is very similar to the corresponding ICMP Destination Unreachable message. In ICMPv6 this is called the Packet Too Big (PTB) message. We will use the simpler ICMPv6 PTB terminology from here onward to refer to either the ICMPv4 (type 3, code 4) message or the ICMPv6 (type 2, code 0) message.
ICMPv4 Host Unreachable (Code 1) and ICMPv6 Address Unreachable (Code 3)
This form of the Destination Unreachable message is generated by a router or host when it is required to send an IP datagram to a host using direct delivery (Chapter 5) but for some reason cannot reach the destination. This situation may arise, for example, because the last-hop router is attempting to send an ARP request to a host that is either missing or down. (This situation is explored in Chapter 4, which describes ARP.) For ICMPv6, which uses a somewhat different mechanism for detecting unresponsive hosts, this message can be the result of a failure in the ND process (see Section 8.5).
ICMPv6 No Route to Destination (Code 0)
[p365]
ICMPv4 Communication Administratively Prohibited (Code 13) and ICMPv6 Communication with Destination Administratively Prohibited (Code 1)
[p365]
ICMPv4 Port Unreachable (Code 3) and ICMPv6 Port Unreachable (Code 4)
The Port Unreachable message is generated when an incoming datagram is destined for an application that is not ready to receive it. This occurs most commonly in conjunction with UDP, when a message is sent to a port number that is not in use by any server process. If UDP receives a datagram and the destination port does not correspond to a port that some process has in use, UDP responds with an ICMP Port Unreachable message.
[p366-370]
ICMPv4 PTB (Code 4)
ICMPv6 PTB (Type 2, Code 0)
ICMPv6 Beyond Scope of Source Address (Code 2)
ICMPv6 Source Address Failed Ingress/Egress Policy (Code 5)
ICMPv6 Reject Route to Destination (Code 6)
Redirect (ICMPv4 Type 5, ICMPv6 Type 137)
ICMP Time Exceeded (ICMPv4 Type 11, ICMPv6 Type 3)
Every IPv4 datagram has a Time-to-Live (TTL) field in its IPv4 header, and every IPv6 datagram has a Hop Limit field in its header (Chapter 5).
As originally conceived, the 8-bit TTL field was to hold the number of seconds a datagram was allowed to remain active in the network before being forcibly discarded (a good thing if forwarding loops are present). Because of an additional rule that said that any router must decrement the TTL field by at least 1, combined with the fact that datagram forwarding times grew to be small fractions of a second, the TTL field has been used in practice as a limitation on the number of hops an IPv4 datagram is allowed to take before it is discarded by a router. This usage was formalized and
ultimately adopted in IPv6.
ICMP Time Exceeded (code 0) messages are generated when a router discards a datagram because the TTL or Hop Limit field is too low (i.e., arrives with value 0 or 1 and must be forwarded). This message is important for the proper operation of the traceroute
tool (called tracert
on Windows). Its format, for both ICMPv4 and ICMPv6, is given in the figure below.
Another less common variant of this message is when a fragmented IP datagram only partially arrives at its destination (all its fragments do not arrive after a period of time). In such cases, a variant of the ICMP Time Exceeded message (code 1) is used to inform the sender that its overall datagram has been discarded. Recall that if any fragment of a datagram is dropped, the entire datagram is lost.
Example: The traceroute
Tool
The traceroute
tool is used to determine the routers used along a path from a sender to a destination. This section discusses the operation of the IPv4 version. The approach involves sending datagrams first with an IPv4 TTL field set to 1 and allowing the expiring datagrams to induce routers along the path to send ICMPv4 Time Exceeded (code 0) messages. Each round, the sending TTL value is increased by 1, causing the routers that are one hop farther to expire the datagrams and generate ICMP messages. These messages are sent from the router’s primary IPv4 address «facing» the sender.
In this example, traceroute
is used to send UDP datagrams from the laptop to the host www.eecs.berkeley.edu
. (an Internet host with IPv4 address 128.32.244.172). This is accomplished using the following command:
Linux% traceroute –m 2 www.cs.berkeley.edu
traceroute to web2.eecs.berkeley.edu (128.32.244.172), 2 hops max,
52 byte packets
1 gw (192.168.0.1) 3.213 ms 0.839 ms 0.920 ms
2 10.0.0.1 (10.0.0.1) 1.524 ms 1.221 ms 9.176 ms
The –m
option instructs traceroute
to perform only two rounds: one using TTL = 1 and one using TTL = 2. Each line gives the information found at the corresponding TTL. For example, line 1 indicates that one hop away a router with IPv4 address 192.168.0.1 was found and that three independent round-trip-time (RTT) measurements (3.213, 0.839, and 0.920ms) were taken. The difference between the first and subsequent times relates to additional work that is involved in the first measurement (i.e., an ARP transaction).
[p377-379]
Parameter Problem (ICMPv4 Type 12, ICMPv6 Type 4)
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) — протокол межсетевых управляющих сообщений.
Протокол IP, который используется для передачи данных на сетевом уровне, обеспечивает сервис передачи данных без гарантии доставки. Если по пути передачи данных с пакетом что-то произойдет, то никаких действий не предпринимается, сообщения об ошибке не отправляются, попыток передать снова этот пакет не предпринимается.
Информация о возникающих ошибках в сети передается по протоколу ICMP. А также протокол ICMP может использоваться для диагностики работы в сети даже, когда в ней не возникают ошибки. Так как IP предоставляет сервис без гарантии доставки, то сообщение об ошибках ICMP не обязаны обрабатываться ни протоколом ICMP ни протоколом IP.
Формат заголовка ICMP
Рассмотрим формат пакета ICMP. Первое поле в заголовке тип сообщения. Оно говорит о том, что произошло в сети, какая ошибка или какое действие по диагностике пытаются выполнить.
Второе поле -код сообщения. В нем подробно описывается тип ошибки, её причина или диагностическое действие. Дальше идёт контрольная сумма, которая используется для проверки правильности доставки. Следующие 4 байта, служебная информация, которая зависит от типа и кода сообщения. В поле данных ICMP, как правило включается фрагмент пакета при передачи которого произошла ошибка.
Типы ICMP — сообщений
Самое важно в пакете ICMP это тип сообщений. Именно тип, говорит о том, что произошло в сети. Есть 2 вида ICMP сообщений. Первый вид это запрос-ответ.
- Например, тип 0 и тип 8 это эхо-ответ и эхо-запрос, которые используются для проверки доступности компьютера в сети.
- Тип 13 и 14 запрос и ответ отметки времени. Эти запросы используются для проверки быстродействия сети. Другой вид это сообщение без запроса.
- Тип 3 это сообщение об ошибке узел назначения недостижим.
- Тип 5 сообщение о новом маршруте, который позволяет быстрее попасть к необходимой сети.
- Тип 9 сообщение о маршрутизаторе. Маршрутизаторы в сети периодически рассылают такие сообщения, чтобы компьютеры, которые находятся в сети могли узнать, какие есть маршрутизаторы.
- Тип 10 запрос сообщения о маршрутизаторе, если компьютер только что подключился к сети, он может не дожидаться периодического сообщения от маршрутизаторов, отправить такой запрос и маршрутизатор сразу отправит ответ о себе.
- Сообщение с типом 11 используется если маршрутизатор отбросил пакет время жизни которого истекло, как правило такая ситуация возникает, если в сети появилась петля.
- Сообщение с типом 12 — проблемы с параметрами, говорит о том, что в заголовке IP какая-то ошибка и маршрутизатор не может отправить такой пакет.
Коды ICMP — сообщений
Следующее поле в заголовке ICMP это код сообщения. Ниже представлено несколько возможных кодов для типа сообщения 3 — узел назначения недостижим. Какие могут быть причины? Причины перечислены ниже на картинке.
Применение ICMP
Большая часть пакетов ICMP формируется и отправляется автоматически сетевым оборудованиям. Но некоторые типы сообщений формируются утилитами, которые применяются для диагностики сети. Рассмотрим утилиты ping и traceroute (в Windows tracert)
Утилита ping
Утилита ping используется, чтобы проверить доступность компьютера в сети. Возможно подключиться к этому компьютеру или нельзя. Ping использует это-протокол ICMP. Компьютер, который хочет проверить доступность другого, отправляет эхо-запрос (тип=8, код=0).
Компьютер, который получил такой запрос, в ответ отправляет эхо-ответ ICMP с типом 0, если эхо-ответ не пришел, значит установить с компьютером соединение по сети невозможно.
Пример использования утилиты ping для проверки возможности подключиться к сайту ВКонтакте. По умолчанию утилита ping запускает 4 эхо-запроса и для каждого эхо-запроса получен эхо-ответ. В ответе указывается некоторая диагностическая информация.
Утилита traceroute
Утилита traceroute позволяет определить маршрут от отправителя к получателю. Под маршрутом имеется в виду перечень всех маршрутизаторов через которые проходит пакет.
Пример работы утилиты traceroute ее windows вариант tracert для определения маршрута к сайту ВКонтакте.
Работа утилиты traceroute
Как утилита traceroute узнает маршрутизатор? Для этого утилита использует ICMP сообщения время жизни истекло. Чтобы этого достичь, сначала отправляется сообщение у которого время жизни установлено в единицу TTL=1.
Пакет доходит до первого маршрутизатора, маршрутизатор уменьшает время жизни TTL=0 и маршрутизатор отбрасывает пакет.
И генерирует сообщение об ошибке ICMP с типом 11, код 0 время жизни истекло. Утилита traceroute из заголовка IP пакета в которого вложен ICMP извлекает IP-адрес маршрутизатора.
На следующем этапе отправляется пакет с временем жизни равным двум TTL=2.
На первом маршрутизаторе время жизни уменьшается до единицы и пакет переходит на второй маршрутизатор.
Второй маршрутизатор снова уменьшает время на 1, время жизни становится нулем. Пакет отбрасывается и уже второй маршрутизатор отправляет сообщение время жизни истекло. Утилита traceroute извлекает адрес второго маршрутизатора из IP заголовка этого сообщения.
И так происходит до тех пор пока пакет не дойдет до узла назначения.
Заключение
Рассмотрели протокол ICMP протокол межсетевых управляющих сообщений. Протокол ICMP используется для сообщения об ошибках, которые происходят в сети и для тестирования работоспособности сети.