ICMP & Ping
ICMP (Internet Control Message Protocol, RFC 792) is the network layer's messaging system. Routers and hosts use it to report errors ("destination unreachable", "time exceeded") and to run diagnostics ("echo request" / "echo reply"). ICMP messages travel inside IP packets with protocol number 1 (ICMPv6 uses 58 and also does the jobs of ARP and parts of DHCP).
Common message types
| Type | Code | Name | Sent when |
|---|---|---|---|
| 0 | 0 | Echo Reply | answering a ping |
| 3 | 0 / 1 / 3 / 4 | Destination Unreachable: network / host / port / fragmentation needed | a packet can't be delivered |
| 5 | 0–3 | Redirect | a router knows a better next hop on the same LAN |
| 8 | 0 | Echo Request | ping |
| 11 | 0 | Time Exceeded (TTL reached 0) | used by traceroute |
The echo request packet
An echo message has an 8-byte header followed by arbitrary data:
| Type (8) | Code (8) | Checksum (16) | Identifier (16) | Sequence (16) | Data ... |The identifier lets the OS match replies to the right ping process; the sequence number increments with each packet. The checksum is the Internet checksum over the whole ICMP message.
import struct
def checksum(data):
if len(data) % 2:
data += b"\0"
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def echo_request(ident, seq, payload):
header = struct.pack("!BBHHH", 8, 0, 0, ident, seq)
csum = checksum(header + payload)
return struct.pack("!BBHHH", 8, 0, csum, ident, seq) + payload
payload = bytes(range(0x10, 0x10 + 48)) + b"ExcelTAD" # 56 bytes like Linux ping
packet = echo_request(ident=0x1a2b, seq=1, payload=payload)
print(len(packet), "bytes of ICMP,", len(packet) + 20, "bytes with the IP header")
print(packet[:8].hex(" "), "...")
print("checksum valid:", checksum(packet) == 0)64 bytes of ICMP, 84 bytes with the IP header
08 00 db 99 1a 2b 00 01 ...
checksum valid: True
That's where ping's famous 56(84) bytes comes from: 56 data bytes, plus the 8-byte ICMP header, plus the 20-byte IP header.
The reply
The target copies the identifier, sequence and data into an echo reply (type 0) and recomputes the checksum. Parsing it back:
import struct
def checksum(data):
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def make_reply(request):
body = b"\x00\x00\x00\x00" + request[4:] # type 0, code 0, checksum 0
csum = checksum(body)
return body[:2] + struct.pack("!H", csum) + body[4:]
def parse(message):
mtype, code, csum, ident, seq = struct.unpack("!BBHHH", message[:8])
names = {0: "echo reply", 8: "echo request"}
return f"{names[mtype]} id=0x{ident:04x} seq={seq} data={len(message) - 8}B ok={checksum(message) == 0}"
request = bytes.fromhex("0800f7fb1a2b0001") + b"ping!!"
request = request[:2] + struct.pack("!H", checksum(request[:2] + b"\0\0" + request[4:])) + request[4:]
reply = make_reply(request)
print(parse(request))
print(parse(reply))echo request id=0x1a2b seq=1 data=6B ok=True
echo reply id=0x1a2b seq=1 data=6B ok=True
Simulating ping
A real ping sends a request every second and measures the round-trip time (RTT). Here is a simulated run against a host whose RTTs we fix in advance, including one lost packet, with the same statistics ping prints:
import statistics
rtts_ms = [11.8, 11.5, None, 12.4, 11.9] # None = no reply (lost)
for seq, rtt in enumerate(rtts_ms, start=1):
if rtt is None:
print(f"Request timeout for icmp_seq={seq}")
else:
print(f"64 bytes from 93.184.215.14: icmp_seq={seq} ttl=56 time={rtt} ms")
received = [r for r in rtts_ms if r is not None]
loss = 100 * (len(rtts_ms) - len(received)) / len(rtts_ms)
print(f"{len(rtts_ms)} packets transmitted, {len(received)} received, {loss:.0f}% packet loss")
print(f"rtt min/avg/max/mdev = {min(received)}/{statistics.mean(received):.3f}/"
f"{max(received)}/{statistics.pstdev(received):.3f} ms")64 bytes from 93.184.215.14: icmp_seq=1 ttl=56 time=11.8 ms
64 bytes from 93.184.215.14: icmp_seq=2 ttl=56 time=11.5 ms
Request timeout for icmp_seq=3
64 bytes from 93.184.215.14: icmp_seq=4 ttl=56 time=12.4 ms
64 bytes from 93.184.215.14: icmp_seq=5 ttl=56 time=11.9 ms
5 packets transmitted, 4 received, 20% packet loss
rtt min/avg/max/mdev = 11.5/11.900/12.4/0.324 ms
Traceroute: TTL as a probe
traceroute (Windows: tracert) sends packets with TTL = 1, 2, 3, … Each router that decrements the TTL to 0 replies with ICMP Time Exceeded, revealing its address. When the probe finally reaches the destination, it answers (with an echo reply, or a port unreachable for UDP probes) and the trace ends.
path = ["192.168.1.1", "100.64.0.1", "203.0.113.9", "198.51.100.30", "93.184.215.14"]
latency_ms = [1.2, 8.7, 9.4, 10.8, 11.6]
def send_probe(ttl):
hop = path[min(ttl, len(path)) - 1]
if ttl < len(path):
return hop, "time exceeded"
return hop, "echo reply"
for ttl in range(1, 10):
hop, answer = send_probe(ttl)
print(f"{ttl:>2} {hop:<15} {latency_ms[ttl - 1]:>5} ms ({answer})")
if answer == "echo reply":
break 1 192.168.1.1 1.2 ms (time exceeded)
2 100.64.0.1 8.7 ms (time exceeded)
3 203.0.113.9 9.4 ms (time exceeded)
4 198.51.100.30 10.8 ms (time exceeded)
5 93.184.215.14 11.6 ms (echo reply)
traceroute -n example.comSample output:
traceroute to example.com (93.184.215.14), 30 hops max, 60 byte packets
1 192.168.1.1 1.214 ms 1.102 ms 1.088 ms
2 100.64.0.1 8.731 ms 8.540 ms 8.902 ms
3 * * *
4 198.51.100.30 10.812 ms 10.777 ms 10.950 ms
5 93.184.215.14 11.611 ms 11.580 ms 11.702 ms* * * means that router didn't reply, often because it is configured to ignore or rate-limit ICMP. It doesn't necessarily mean packets are being lost.
Note: Blocking all ICMP on a firewall is a common mistake. It breaks Path MTU Discovery ("fragmentation needed" messages), which causes connections to hang when large packets are sent. Allow at least types 3 and 11, and rate-limit echo requests if you're worried about abuse.
Test yourself
What ICMP type is an echo request (ping)?
- 0
- 3
- 8
- 11
Which ICMP message lets traceroute discover routers?
- Echo reply
- Redirect
- Time Exceeded
- Source quench
Linux ping says '56(84) bytes'. What are the extra 28 bytes?
- Ethernet header and FCS
- ICMP header (8) and IPv4 header (20)
- TCP and IP headers
- Padding