RawPing.Packet (raw_ping v0.2.0)

Copy Markdown View Source

ICMP packet construction and parsing.

Handles building ICMP echo request packets and parsing echo reply packets.

ICMP Echo Request/Reply Format

0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Type      |     Code      |          Checksum             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Identifier          |        Sequence Number        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Data ...
+-+-+-+-+-+-+-+-
  • Type 8, Code 0: Echo Request
  • Type 0, Code 0: Echo Reply

Summary

Functions

Build an ICMP echo request packet.

Calculate the ICMP checksum (one's complement of one's complement sum).

Parse an ICMP echo reply packet.

Functions

build_echo_request(id, seq, payload_size \\ 56)

@spec build_echo_request(non_neg_integer(), non_neg_integer(), non_neg_integer()) ::
  binary()

Build an ICMP echo request packet.

Parameters

  • id - Identifier (16-bit)
  • seq - Sequence number (16-bit)
  • payload_size - Size of payload data in bytes

Returns a binary packet ready to send.

calculate_checksum(data)

@spec calculate_checksum(binary()) :: non_neg_integer()

Calculate the ICMP checksum (one's complement of one's complement sum).

parse_echo_reply(data)

@spec parse_echo_reply(binary()) ::
  {:ok, non_neg_integer(), non_neg_integer(), non_neg_integer()}
  | {:error, term()}

Parse an ICMP echo reply packet.

The input includes the IP header (20 bytes typically) followed by the ICMP packet.

Returns {:ok, id, seq, ttl} or {:error, reason}.