ICMP: Протокол межсетевых управляющих сообщений
ICMP является дополнительным протоколом к IP (Internet Protocol). Как и IP, ICMP находится на сетевом уровне модели OSI .
ICMP предназначен для отправки контрольных и тестовых сообщений по IP-сетям.
В отличие от протоколов транспортного уровня TCP (Протокол управления передачей) и UDP (User Datagram Protocol), которые работают поверх IP, ICMP существует рядом с IP.
Возможность понимать ICMP является требованием для любого IP-совместимого сетевого устройства. Однако многие устройства безопасности, такие как брандмауэры, блокируют или отключают все или часть функций ICMP для целей безопасности.
Типы сообщений ICMP
ICMP работает, отправляя и получая ограниченное количество типов сообщений. Типы сообщений ICMP определены в IAMA ICMP Type Numbers.
Наиболее распространенными типами сообщений ICMP являются:
|6||Альтернативный адрес узла|
|11||Время жизни дейтаграммы истекло|
|13||Запрос метки времени|
|14||Ответ с меткой времени|
|17||Запрос адресной маски|
|18||Отклик на запрос адресной маски|
ICMP Echo Request и Echo Reply
Двумя наиболее важными сообщениями ICMP являются Echo Request (8) и Echo Reply (0).
Echo Request и Echo Reply используются командой `ping` для проверки сетевого подключения.
Linux Ping Command Tutorial with Examples
Most Linux users are familiar with the ping command and know how to use it in its basic form. However, there are many additional ping options and variations. In this guide, we will walk you through some of the most useful Linux ping commands with examples.
The commands in this article work with any UNIX or Linux distribution. The test system we used to provide the examples and output samples is Ubuntu 18.04.2 LTS.
- Linux or UNIX-like system
- Access to a terminal
- A user with the necessary permissions to run the commands
How ping Works in Linux
The Linux ping command is a simple utility used to check whether a network is available and if a host is reachable. With this command, you can test if a server is up and running. It also helps with troubleshooting various connectivity issues.
The ping command allows you to:
- Test your internet connection.
- Check if a remote machine is online.
- Analyze if there are network issues, such as dropped packages or high latency.
When you try to “ping” a remote host, your machine starts sending ICMP echo requests and waits for a response. If the connection is established, you receive an echo reply for every request.
The output for the ping command contains the amount of time it takes for every packet to reach its destination and return.
The terminal keeps printing the responses until interrupted. After every session, there are a few lines with ping statistics.
How to Use the ping Command
The basic ping syntax includes ping followed by a hostname, a name of a website, or the exact IP address.
Hence, to check whether a remote host is up, in this case, google.com, type in your terminal:
Press Ctrl + C on your keyboard to stop the process.
1. from : The destination and its IP address. Note that the IP address may be different for a website depending on your geographical location.
2. icmp_seq=1 : The sequence number of each ICMP packet. Increases by one for every subsequent echo request.
3. ttl=52 : The Time to Live value from 1 to 255. It represents the number of network hops a packet can take before a router discards it.
4. time=7.68 ms : The time it took a packet to reach the destination and come back to the source. Expressed in milliseconds.
ping Commands in Linux with Examples
ping “localhost” to Check Local Network
If you encounter issues reaching a website or a remote machine, you can ping localhost to confirm you have a network connection. Use one of the three ways to check the local network interface:
- ping 0 – This is the quickest way to ping localhost. Once you type this command, the terminal resolves the IP address and provides a response.
- ping localhost – You can use the name to ping localhost. The name refers to your computer, and when we use this command, we say: “ping this computer.”
- ping 127.0.0.1 – Some people prefer using the IP address 127.0.0.1 to ping localhost.
Whichever method you choose, the ping output looks the same.
Specify the Internet Protocol
IPv6 is the IP address alphanumeric format that will supersede IPv4. The reason for this is there is a limited number of IPv4 address, and we are running out of possible combinations.
To request IPv6 or IPv4 address, add -6 or -4 after the ping command and before a hostname/IP.
Change Time Interval Between Ping Packets
The default interval between each ping request is set to one second. You can increase or decrease that time using the -i switch. To decrease the ping interval, use values lower than 1.
To increase the ping interval, enter any value higher than 1.
Change Ping Packet Size
In some scenarios, you may want to use -s to increase the packet size from the default value of 56 (84) bytes. The number in parenthesis represents the ping bytes sent including 28 bytes of the header packet.
For example, to increase the packet size to 1000 bytes:
You get this output:
This command is useful when testing network performance. You can test if a network link throttles when you increase the packet size to a few thousand bytes.
Flood a Network Using ping to Test Performance
You can use ping flood to test your network performance under heavy load.
Ping flood -f option requires root to execute. Otherwise, apply sudo to your ping command to flood a host. This command sends a large number of packets as soon as possible.
The output prints a dot for every sent package, and a backspace for every response. The statistics line shows a summary of the ping command.
How to Limit the Number of Pings
The default setting for the ping command is to keep sending the request until you interrupt it. You can limit the number of pings using one of the two methods.
Limit Number of Ping Packets
To make the ping command automatically stop after it sends a certain number of packets, use -c and a number. This sets the desired amount of ping requests, as shown in this example:
As you can see on the image above, the ping command stopped sending packets after two requests.
Set Time Limit for ping Command
To stop receiving a ping output after a specific amount of time, add -w and an interval in seconds to your command.
For example, to stop printing ping results after 25 seconds, enter the ping command:
Other Uses for ping
Suppress Ping Output to Print only Summary Statistics
If you do not want to clog your screen with information for every packet, use the -q switch to display the summary only.
The -q option prints one line with the regular ping information and then provides the statistics at the end. The letter “q” in this command stands for “quiet” output.
We usually combine the quiet output with other options. In this case, we will limit the ping to send 10 packets and suppress the output.
Add Timestamp Before Each Line in ping Output
If you want to note the time of day when you execute the ping command, add the -D option.
This prints a timestamp in UNIX format before each line.
Note: You need to use uppercase D, as these commands are case sensitive.
Get an Audible Ping When a Host is Reachable
When you use the -a switch, the system plays a sound when there is a response from a host.
An audible ping is useful when you are troubleshooting network issues and do not want to look at the screen until there is a response.
The output looks the same as a regular ping command output.
Show Ping Version and Exit
At any time, you can check the version of the ping tool on your system.
Append -V to the ping command to display the version of this utility.
Commonly used Ping Commands include:
|Ping Option||What The Command Does|
|a||Generates a sound when the peer can be reached.|
|b||Allows to ping a broadcast IP address.|
|B||Prevents the ping to change the source address of the probe.|
|c (count)||Limits the number of sent ping requests.|
|d||Sets the SO-DEBUG option on the used socket.|
|f||Floods the network by sending hundreds of packets per second.|
|i (interval)||Specifies an interval between successive packet transmissions. The default value is one second.|
|I (interface address)||Sets the source IP address to the specified interface IP address. The option is required when pinging IPv6 link local address. You can use an IP address or name of the device.|
|l (preload)||Defines the number of packets to send without waiting for a reply. To specify a value higher than 3, you need superuser permissions.|
|n||Displays IP addresses in the ping output rather than hostnames.|
|q||Shows a quiet output. One ping line is displayed and the summary of the ping command at the end.|
|T (ttl)||Sets the Time To Live.|
|v||Provides verbose output.|
|V||Displays the ping version and exits to a new command prompt line.|
|w (deadline)||Specifies a time limit before the ping command exits, regardless of how many packets have been sent or received.|
|W (timeout)||Determines the time, in seconds, to wait for a response.|
Now you know how to use the Linux ping command. The examples in the tutorial should help you understand how to use “ping” on a day-to-day basis.
Ping helps you check the network connectivity both locally and with a remote host.
To view the complete list with the remaining ping options, run the man command man ping inside the terminal.
Understanding Ping Command and ICMP with Examples
Ping is a tool commonly used to find the status of a device on a network. Ping is based on the ICMP protocol. When a Ping process request is sent out as an ICMP echo to the target device, it replies with an ICMP echo reply if the device is available.
Purpose of Ping command
ping is used to send a test packet, or echo packet, to a device to find out whether it is reachable and how long the packet takes to reach the device. There are two important purposes.
- test the network availability to the device
- network latency between two devices
Ping command is a simple way to check whether we have access to the particular host. But this method works only if ICMP and ping is enabled in that network. If ICMP is disabled, we can not get a proper response.
Example of Ping Command
$ ping google.com
PING google.com (188.8.131.52): 56 data bytes
64 bytes from 184.108.40.206: icmp_seq=0 ttl=100 time=87.363 ms
64 bytes from 220.127.116.11: icmp_seq=1 ttl=100 time=89.754 ms
64 bytes from 18.104.22.168: icmp_seq=2 ttl=100 time=90.045 ms
— google.com ping statistics —
4 packets transmitted, 3 packets received, 25.0% packet loss
round-trip min/avg/max/stddev = 87.363/89.054/90.045/1.202 ms
- from: The destination and its IP address. Note that the IP address may be different for a website depending on our geographical location.
- icmp_seq=0: The sequence number of each ICMP packet. Increases by one for every subsequent echo request.
- ttl=100: The Time to Live value from 1 to 255. It represents the number of networks hops a packet can take before a router discards it.
- time=87.68 ms: The time it took a packet to reach the destination and come back to the source. Expressed in milliseconds.
The ping command can also be used to check for packet loss. When you run the ping command, it sends a series of packets to the specified destination and waits for a response.
If any of the packets are lost or do not receive a response, the ping command will report the percentage of packets lost.
For example, if you run the ping command and it reports “0% packet loss,” that means all of the packets that were sent were received successfully. However, if it reports “10% packet loss,” that means 10% of the packets that were sent did not receive a response and were lost.
So, the ping command is a useful tool for checking network connectivity and identifying any packet loss issues that may be affecting your connection.
Change Ping Packet Size in Ping Command
In some scenarios, we may want to use -s to increase the packet size from the default value of 64 bytes.
For example, to increase the packet size to 1000 bytes:
ping -s 1000 google.com
ICMP Packet Structure
ICMP (Internet Control Message Protocol) is a protocol used by network devices, such as routers and hosts, to communicate error messages and operational information about the network.
It is an integral part of the Internet Protocol (IP) suite and is used by various network diagnostic tools such as ping, traceroute, and pathping.
ICMP messages are typically used for network troubleshooting and management, helping to identify and resolve issues related to network connectivity, packet loss, and latency.
In this part, we will explore ICMP in detail, including its message format, types, and examples of how it is used in practice.
ICMP is part of IP, and it relies on IP to transmit its messages. ICMP contains a relatively small header that changes depending on its purpose. The ICMP header contains the following fields:
- Type The type or classification of the ICMP message, based on the RFC specification
- Code The subclassification of the ICMP message, based on the RFC specification
- Checksum Used to ensure that the contents of the ICMP header and data are intact upon arrival
- Variable A portion that varies depending on the Type and Code fields
Let’s see an example of ICMP packet.
00 0c 29 f8 1c 7c 00 0c 29 23 c1 05 08 00 45 00
00 3c 02 04 00 00 80 01 6a 2e c0 a8 01 01 c0 a8
01 02 08 00 28 b6 7c 01 00 00 00 00 09 00 00 00
00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a
1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a
2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37
This is a hexadecimal dump of the packet. ICMP packets are often used for diagnostic or error reporting purposes in networking.
In this example, the packet contains the following fields:
|Ethernet||Source MAC address: 00 0c 29 f8 1c 7c|
|Destination MAC address: 00 0c 29 23 c1 05|
|IP||Source IP address: 192.168.1.1|
|Destination IP address: 192.168.1.2|
|ICMP||Type: 8 (echo request)|
|Checksum: 28 b6|
|Payload||00 00 00 00 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b|
|1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f|
|30 31 32 33 34 35 36 37|
Each ICMP message has a specific type and code that determines its purpose.
The type field defines the general category of the ICMP message, while the code field provides additional information about the specific message type.
For example, an ICMP message with type 3 (Destination Unreachable) might have a code of 0 (Net Unreachable) or 1 (Host Unreachable) to further specify the reason for the error.
|ICMP Type and Code||Description|
|Type 8, Code 0; Type 0, Code 0||Echo request and Echo reply|
|Type 3, various codes||Destination unreachable|
|Type 11, Code 0; Type 11, Code 1||Time exceeded|
|Type 5, various codes||Redirect message|
|Type 12, various codes||Parameter problem|
Capture Ping Packet with tcpdump Command
We can use this tcpdump command to filter all ping packets. Here we use eth0 network interface in all our examples. Please change it based on the environment.
# tcpdump -i eth0 icmp
To filter ICMP echo-requests, we can use this tcpdump command.
# tcpdump -i eth0 «icmp == 8»
These are the packets we get captured with tcpdump command.
14:37:14.555295 IP 10.79.101.23 > 22.214.171.124: ICMP echo request, id 61205, seq 0, length 6414:37:15.557948 IP 10.79.101.23 > 126.96.36.199: ICMP echo request, id 61205, seq 1, length 6414:37:16.562905 IP 10.79.101.23 > 188.8.131.52: ICMP echo request, id 61205, seq 2, length 64
Ping Command Options
Here are 5 common ping command options with examples:
“-c” option: This option specifies the number of packets to send. For example, to send 5 packets, you can use the following command:
ping -c 5 google.com
“-i” option: This option sets the interval between successive packets. For example, to send packets at an interval of 3 second, you can use the following command:
ping -i 3 google.com
-w deadline: It specifys a timeout, in seconds, before ping exits regardless of how many packets have been sent or received. In this case ping does not stop after count packet are sent, it waits either for deadline expire or until count probes are answered or for some error notification from network.
The “-W” option in the ping command specifies the timeout in seconds for each packet sent. It sets the amount of time that the ping command waits for a response after sending each packet. If a response is not received within the specified timeout period, the packet is considered lost.
6.3. IP Keywords¶
The ttl keyword is used to check for a specific IP time-to-live value in the header of a packet. The format is:
At the end of the ttl keyword you can enter the value on which you want to match. The Time-to-live value determines the maximal amount of time a packet can be in the Internet-system. If this field is set to 0, then the packet has to be destroyed. The time-to-live is based on hop count. Each hop/router the packet passes subtracts one of the packet TTL counter. The purpose of this mechanism is to limit the existence of packets so that packets can not end up in infinite routing loops.
Example of the ttl keyword in a rule:
With the ipopts keyword you can check if a specific IP option is set. Ipopts has to be used at the beginning of a rule. You can only match on one option per rule. There are several options on which can be matched. These are:
|eol||End of List|
|esec||IP Extended Security|
|lsrr||Loose Source Routing|
|ssrr||Strict Source Routing|
|any||any IP options are set|
Format of the ipopts keyword:
Example of ipopts in a rule:
Every packet has a source IP-address and a destination IP-address. It can be that the source IP is the same as the destination IP. With the sameip keyword you can check if the IP address of the source is the same as the IP address of the destination. The format of the sameip keyword is:
Example of sameip in a rule:
With the ip_proto keyword you can match on the IP protocol in the packet-header. You can use the name or the number of the protocol. You can match for example on the following protocols:
For the complete list of protocols and their numbers see http://en.wikipedia.org/wiki/List_of_IP_protocol_numbers
Example of ip_proto in a rule:
The named variant of that example would be:
Sticky buffer to match on the whole IPv4 header.
This example looks if byte 9 of IPv4 header has value 3A. That means that the IPv4 protocol is ICMPv6.
Sticky buffer to match on the whole IPv6 header.
With the id keyword, you can match on a specific IP ID value. The ID identifies each packet sent by a host and increments usually with one with each packet that is being send. The IP ID is used as a fragment identification number. Each packet has an IP ID, and when the packet becomes fragmented, all fragments of this packet have the same ID. In this way, the receiver of the packet knows which fragments belong to the same packet. (IP ID does not take care of the order, in that case offset is used. It clarifies the order of the fragments.)
Example of id in a rule:
The geoip keyword enables (you) to match on the source, destination or source and destination IPv4 addresses of network traffic, and to see to which country it belongs. To be able to do this, Suricata uses the GeoIP2 API of MaxMind.
The syntax of geoip:
So, you can see you can use the following to make clear on which direction you would like to match
|both||Both directions have to match with the given geoip(s)|
|any||One of the directions has to match with the given geoip(s).|
|dest||If the destination matches with the given geoip.|
|src||The source matches with the given geoip.|
The keyword only supports IPv4. As it uses the GeoIP2 API of MaxMind, libmaxminddb must be compiled in. You must download and install the GeoIP2 or GeoLite2 database editions desired. Visit the MaxMind site at https://dev.maxmind.com/geoip/geoip2/geolite2/ for details.
You must also supply the location of the GeoIP2 or GeoLite2 database file on the local system in the YAML-file configuration (for example):
6.3.9. fragbits (IP fragmentation)¶
With the fragbits keyword, you can check if the fragmentation and reserved bits are set in the IP header. The fragbits keyword should be placed at the beginning of a rule. Fragbits is used to modify the fragmentation mechanism. During routing of messages from one Internet module to the other, it can occur that a packet is bigger than the maximal packet size a network can process. In that case, a packet can be send in fragments. This maximum of the packet size is called Maximal Transmit Unit (MTU).
You can match on the following bits:
Matching on this bits can be more specified with the following modifiers:
Example of fragbits in a rule:
With the fragoffset keyword you can match on specific decimal values of the IP fragment offset field. If you would like to check the first fragments of a session, you have to combine fragoffset 0 with the More Fragment option. The fragmentation offset field is convenient for reassembly. The id is used to determine which fragments belong to which packet and the fragmentation offset field clarifies the order of the fragments.
You can use the following modifiers:
Format of fragoffset:
Example of fragoffset in a rule:
The tos keyword can match on specific decimal values of the IP header TOS field. The tos keyword can be have a value from 0 — 255. This field of the IP header has been updated by rfc2474 to include functionality for Differentiated services. Note that the value of the field has been defined with the right-most 2 bits having the value 0. When specifying a value for tos, ensure that the value follows this.
E.g, instead of specifying the decimal value 34 (hex 22), right shift twice and use decimal 136 (hex 88).
You can specify hexadecimal values as with a leading x , e.g, x88 .
Example of tos in a rule:
Example of tos with negated values:
6.4. TCP keywords¶
The seq keyword can be used in a signature to check for a specific TCP sequence number. A sequence number is a number that is generated practically at random by both endpoints of a TCP-connection. The client and the server both create a sequence number, which increases with one with every byte that they send. So this sequence number is different for both sides. This sequence number has to be acknowledged by both sides of the connection. Through sequence numbers, TCP handles acknowledgement, order and retransmission. Its number increases with every data-byte the sender has send. The seq helps keeping track of to what place in a data-stream a byte belongs. If the SYN flag is set at 1, than the sequence number of the first byte of the data is this number plus 1 (so, 2).
Example of seq in a signature:
Example of seq in a packet (Wireshark):
The ack is the acknowledgement of the receipt of all previous (data)-bytes send by the other side of the TCP-connection. In most occasions every packet of a TCP connection has an ACK flag after the first SYN and a ack-number which increases with the receipt of every new data-byte. The ack keyword can be used in a signature to check for a specific TCP acknowledgement number.
Example of ack in a signature:
Example of ack in a packet (Wireshark):
The window keyword is used to check for a specific TCP window size. The TCP window size is a mechanism that has control of the data-flow. The window is set by the receiver (receiver advertised window size) and indicates the amount of bytes that can be received. This amount of data has to be acknowledged by the receiver first, before the sender can send the same amount of new data. This mechanism is used to prevent the receiver from being overflowed by data. The value of the window size is limited and can be 2 to 65.535 bytes. To make more use of your bandwidth you can use a bigger TCP-window.
The format of the window keyword:
Example of window in a rule:
Match on the TCP MSS option value. Will not match if the option is not present.
The format of the keyword:
Sticky buffer to match on the whole TCP header.
This example starts looking after the fixed portion of the header, so into the variable sized options. There it will look for the MSS option (type 2, option len 4) and using a byte_test determine if the value of the option is lower than 536. The tcp.mss option will be more efficient, so this keyword is meant to be used in cases where no specific keyword is available.
6.5. UDP keywords¶
Sticky buffer to match on the whole UDP header.
This example matches on the length field of the UDP header. In this case the length of 8 means that there is no payload. This can also be matched using dsize:0; .
6.6. ICMP keywords¶
ICMP (Internet Control Message Protocol) is a part of IP. IP at itself is not reliable when it comes to delivering data (datagram). ICMP gives feedback in case problems occur. It does not prevent problems from happening, but helps in understanding what went wrong and where. If reliability is necessary, protocols that use IP have to take care of reliability themselves. In different situations ICMP messages will be send. For instance when the destination is unreachable, if there is not enough buffer-capacity to forward the data, or when a datagram is send fragmented when it should not be, etcetera. More can be found in the list with message-types.
There are four important contents of a ICMP message on which can be matched with corresponding ICMP-keywords. These are: the type, the code, the id and the sequence of a message.
The itype keyword is for matching on a specific ICMP type (number). ICMP has several kinds of messages and uses codes to clarify those messages. The different messages are distinct by different names, but more important by numeric values. For more information see the table with message-types and codes.
The format of the itype keyword:
Example This example looks for an ICMP type greater than 10:
Example of the itype keyword in a signature:
The following lists all ICMP types known at the time of writing. A recent table can be found at the website of IANA
|6||Alternate Host Address|
|17||Address Mask Request|
|18||Address Mask Reply|
|31||Datagram Conversion Error|
|32||Mobile Host Redirect|
|35||Mobile Registration Request|
|36||Mobile Registration Reply|
|37||Domain Name Request|
|38||Domain Name Reply|
|41||Experimental mobility protocols such as Seamoby|
With the icode keyword you can match on a specific ICMP code. The code of a ICMP message clarifies the message. Together with the ICMP-type it indicates with what kind of problem you are dealing with. A code has a different purpose with every ICMP-type.
The format of the icode keyword:
Example: This example looks for an ICMP code greater than 5:
Example of the icode keyword in a rule:
The following lists the meaning of all ICMP types. When a code is not listed, only type 0 is defined and has the meaning of the ICMP code, in the table above. A recent table can be found at the website of IANA
|ICMP Code||ICMP Type||Description|
|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|
|9||Communication with Destination Network is Administratively Prohibited|
|10||Communication with Destination Host is Administratively Prohibited|
|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|
|5||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|
|9||0||Normal router advertisement|
|16||Doesn’t route common traffic|
|11||0||Time to Live exceeded in Transit|
|1||Fragment Reassembly Time Exceeded|
|12||0||Pointer indicates the error|
|1||Missing a Required Option|
With the icmp_id keyword you can match on specific ICMP id-values. Every ICMP-packet gets an id when it is being send. At the moment the receiver has received the packet, it will send a reply using the same id so the sender will recognize it and connects it with the correct ICMP-request.