Complete ICMP probe controls and add IPv6 support

This commit is contained in:
Dandaedre 2026-09-17 16:52:42 +02:00
parent 81ac0b787d
commit 2c7343f57d
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
4 changed files with 835 additions and 236 deletions

View File

@ -3,7 +3,7 @@ name = "rping"
version = "0.1.0"
edition = "2024"
rust-version = "1.98"
description = "A small IPv4 ICMP ping utility"
description = "A small IPv4 and IPv6 ICMP packet utility"
license = "MIT"
[dependencies]

View File

@ -1,18 +1,14 @@
# rping
A small IPv4 ICMP ping utility. It sends one packet, waits up to one second for a response, and prints the packet bytes, ICMP fields, and elapsed time.
A small ICMP packet tool for IPv4 and IPv6. It builds packets from explicit fields and payload bytes, sends one or more probes, matches their replies or ICMP errors, and can show the bytes without opening a socket.
## Build
Install [Rust with rustup](https://www.rust-lang.org/tools/install), then run:
```sh
cargo build --locked --release
```
The repository pins Rust 1.98.1 and uses the Rust 2024 edition. Rustup installs the required toolchain automatically. Dependencies are recorded in `Cargo.lock`.
Linux is the primary runtime target. The default mode uses an ICMP datagram socket; your system must permit ping sockets for your user (on Linux, through `net.ipv4.ping_group_range`). Raw mode requires root or `CAP_NET_RAW`. IPv6 is not supported.
Rust 1.98.1 is pinned in `rust-toolchain.toml`. Linux is the primary runtime target. Live datagram mode needs permission to create ping sockets (`net.ipv4.ping_group_range` and, for IPv6, an ICMPv6 datagram socket). Raw mode needs root or `CAP_NET_RAW`.
## Usage
@ -20,42 +16,57 @@ Linux is the primary runtime target. The default mode uses an ICMP datagram sock
rping [OPTIONS] <DESTINATION>
```
Use an IPv4 address or a hostname with an IPv4 address. When running from the checkout, use `cargo run --` or `./target/release/rping`:
```sh
cargo run -- 127.0.0.1
cargo run -- 127.0.0.1 --payload "hello world" --size 64
./target/release/rping 127.0.0.1 --identifier 4660 --sequence 1
sudo ./target/release/rping 127.0.0.1 --raw
cargo run -- --help
# Inspect two exact-size IPv4 probes without DNS or socket privileges.
cargo run -- 127.0.0.1 --payload-hex '00 ff 01' --padding none --count 2 --output hex --dry-run
# Inspect IPv6 packets as newline-delimited JSON.
cargo run -- ::1 --family v6 --payload-hex '00 ff' --padding none --output json --dry-run
# Send four echo probes at 500 ms intervals, with a hop limit of 16.
cargo run -- ::1 --family v6 --count 4 --interval-ms 500 --ttl 16
# Use a raw socket when the ICMP identifier must be controlled.
sudo ./target/release/rping 127.0.0.1 --raw --identifier 4660 --sequence 1
```
| Option | Meaning | Default |
| --- | --- | --- |
| `-t, --type <TYPE>` | ICMP type, as a decimal byte; 8 is an echo request | `8` |
| `-i, --identifier <IDENTIFIER>` | Decimal 16-bit identifier | `16962` (`0x4242`) |
| `-q, --sequence <SEQUENCE>` | Decimal 16-bit sequence number | `16962` (`0x4242`) |
| `-p, --payload <PAYLOAD>` | UTF-8 text; remaining space is zero-filled | Random alphanumeric bytes |
| `-s, --size <SIZE>` | Total ICMP size, including the 8-byte header; 8–65515 bytes | `64` |
| `--family` | `auto`, `v4`, or `v6`; auto uses the first resolved address | `auto` |
| `-t, --type` | ICMP type | `8` for IPv4, `128` for IPv6 |
| `--code` | ICMP code | `0` |
| `-i, --identifier` | 16-bit identifier | `16962` (`0x4242`) |
| `-q, --sequence` | Initial 16-bit sequence number; increments per probe | `16962` |
| `-p, --payload` | UTF-8 payload bytes | None |
| `--payload-hex` | Hex bytes; spaces, colons and underscores allowed | None |
| `--payload-file` | Read binary payload from file | None |
| `-s, --size` | Total ICMP size, header included; 8–65515 bytes | `64` unless padding is `none` |
| `--padding` | `auto`, `zero`, `random`, or `none` | `auto` |
| `-c, --count` | Number of probes | `1` |
| `--interval-ms` | Time between probe starts, in milliseconds | `1000` |
| `--timeout-ms` | Per-probe response deadline, in milliseconds | `1000` |
| `--ttl` | IPv4 TTL or IPv6 unicast hop limit, 1–255 | System default |
| `--output` | `summary`, `hex`, or `json` | `summary` |
| `--raw` | Use a raw ICMP socket | Off |
| `-h, --help` | Show usage and options | |
| `-V, --version` | Show version | |
| `--dry-run` | Build packets without DNS or socket access | Off |
The payload must fit within `--size` minus 8 bytes; text is measured in UTF-8 bytes. An empty payload generates random data. The ICMP code is always zero. The OS may replace the identifier and checksum in datagram mode. Large packets may exceed the network's MTU.
Payload options are mutually exclusive. `auto` fills unused bytes with random alphanumeric bytes when no payload was supplied; otherwise it zero-fills them. `random` and `zero` select explicit padding. `none` makes the packet exactly eight bytes plus the payload; if `--size` is given, it must match. The sequence wraps after 65535. `--count` is limited to 65536 so one run does not reuse a sequence number.
The destination is positional. Older README examples using `--dest`, `--request`, or `--data` were incorrect; these are not supported options. Invalid arguments, socket errors, and timeouts return a nonzero exit status.
The output modes are a per-probe summary, full hex dumps plus summaries, or newline-delimited JSON with one object per probe and a final summary object. JSON probe objects include the status, sequence, requested packet bytes, and received bytes when available. A run exits 0 when every probe receives a matching reply, or when all probes are dry runs. A timeout, ICMP error, invalid input, or socket failure exits nonzero. Unrelated or malformed packets are ignored until each probe's deadline.
## Development and CI
The hex dump shows the ICMP packet passed to the socket. In IPv4 datagram mode, Linux may rewrite the identifier and checksum. Use `--raw` for control over those fields. The kernel supplies the IPv4 header in both modes. For ICMPv6, the kernel calculates the mandatory checksum using the IPv6 pseudo-header, so dry-run output shows zero in the checksum field. It is not the complete on-wire ICMPv6 packet. Sending non-echo types or nonzero codes requires `--raw`; `--dry-run` can inspect them without privileges. Only matching echo replies and matching ICMP errors are recognized as responses. A dry run with a hostname defaults to IPv4 unless `--family v6` is specified, because dry runs do not resolve hostnames.
## Development
```sh
cargo fmt --all
cargo fmt --all -- --check
cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
cargo build --locked --release --all-features
```
The Jenkins pipeline applies formatting in its workspace, then runs the remaining checks on a `rust_nodocker` worker with rustup installed and access to the Rust distribution server and crates.io. Formatting differences do not fail the build. It uses the repository's toolchain without changing the worker's default. The existing `publishChecks` step requires the Jenkins Checks API plugin and a configured SCM checks publisher. Tests do not require network access or elevated socket privileges; CI does not run live pings.
Tests do not need network access. CI does not run live pings.
## License

View File

@ -1,29 +1,88 @@
use clap::{CommandFactory, Parser, error::ErrorKind};
use clap::{Parser, ValueEnum};
use std::{fs, io, path::PathBuf, time::Duration};
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Padding {
#[default]
Auto,
Zero,
Random,
None,
}
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Family {
#[default]
Auto,
V4,
V6,
}
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Output {
#[default]
Summary,
Hex,
Json,
}
#[derive(Debug, Parser)]
#[command(version, about, arg_required_else_help = true)]
pub struct Config {
/// Destination IPv4 address or hostname
/// Destination IP address or hostname
#[arg(value_name = "DESTINATION")]
pub dest_addr: String,
/// ICMP type (8 is an echo request); code is always 0
#[arg(short = 't', long = "type", default_value_t = 8)]
pub ping_type: u8,
/// ICMP identifier (decimal; the OS may replace it in datagram mode)
/// ICMP type (8 is an echo request)
#[arg(short = 't', long = "type")]
pub ping_type: Option<u8>,
/// ICMP code
#[arg(long, default_value_t = 0)]
pub code: u8,
/// ICMP identifier (the OS may replace it in datagram mode)
#[arg(short = 'i', long, default_value_t = 16962)]
pub identifier: u16,
/// ICMP sequence number (decimal)
/// ICMP sequence number
#[arg(short = 'q', long, default_value_t = 16962)]
pub sequence: u16,
/// UTF-8 payload; unused space is zero-filled
#[arg(short = 'p', long)]
/// UTF-8 payload
#[arg(short = 'p', long, conflicts_with_all = ["payload_hex", "payload_file"])]
pub payload: Option<String>,
/// Total ICMP packet size in bytes, including the 8-byte header
#[arg(short = 's', long = "size", default_value = "64", value_parser = parse_size)]
pub payload_size: usize,
/// Hexadecimal payload bytes (spaces, colons and underscores allowed)
#[arg(long, conflicts_with = "payload_file")]
pub payload_hex: Option<String>,
/// Read payload bytes from a file
#[arg(long)]
pub payload_file: Option<PathBuf>,
/// Total ICMP packet size, including the 8-byte header (8–65515)
#[arg(short = 's', long = "size", value_parser = parse_size)]
pub size: Option<usize>,
/// Padding: auto, zero, random, or none
#[arg(long, value_enum, default_value_t = Padding::Auto)]
pub padding: Padding,
/// Use a raw ICMP socket (requires root or CAP_NET_RAW on Linux)
#[arg(long = "raw")]
pub raw_packet: bool,
#[arg(long)]
pub raw: bool,
/// Print the packet without opening a socket
#[arg(long)]
pub dry_run: bool,
/// Response timeout in milliseconds
#[arg(long, default_value_t = 1000, value_parser = clap::value_parser!(u64).range(1..))]
pub timeout_ms: u64,
/// Number of probes
#[arg(short = 'c', long, default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..))]
pub count: u32,
/// Time between probe starts in milliseconds
#[arg(long, default_value_t = 1000)]
pub interval_ms: u64,
/// IP time to live (IPv4) or hop limit (IPv6)
#[arg(long, value_parser = clap::value_parser!(u8).range(1..))]
pub ttl: Option<u8>,
/// Address family
#[arg(long, value_enum, default_value_t = Family::Auto)]
pub family: Family,
/// Output format
#[arg(long, value_enum, default_value_t = Output::Summary)]
pub output: Output,
}
fn parse_size(value: &str) -> Result<usize, String> {
@ -36,21 +95,88 @@ fn parse_size(value: &str) -> Result<usize, String> {
Ok(size)
}
pub fn parse_all_arguments() -> Config {
let config = Config::parse();
if config
.payload
.as_ref()
.is_some_and(|p| p.len() > config.payload_size - 8)
{
Config::command()
.error(
ErrorKind::ValueValidation,
"payload exceeds --size minus the 8-byte ICMP header",
)
.exit();
impl Config {
pub fn payload_bytes(&self) -> io::Result<Vec<u8>> {
if let Some(s) = &self.payload {
Ok(s.as_bytes().to_vec())
} else if let Some(s) = &self.payload_hex {
let hex: String = s
.chars()
.filter(|c| !matches!(c, ' ' | ':' | '_' | '\n' | '\t'))
.collect();
if !hex.len().is_multiple_of(2) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"payload hex must contain complete byte pairs",
));
}
hex.as_bytes()
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidInput, "invalid payload hex")
})
})
.collect()
} else if let Some(path) = &self.payload_file {
fs::read(path)
} else {
Ok(Vec::new())
}
}
config
pub fn packet_size(&self, payload_len: usize) -> io::Result<usize> {
let size = if matches!(self.padding, Padding::None) {
self.size.unwrap_or(payload_len.saturating_add(8))
} else {
self.size.unwrap_or(64)
};
if !(8..=65515).contains(&size)
|| payload_len > size - 8
|| (matches!(self.padding, Padding::None) && payload_len != size - 8)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"packet size must be 8..=65515, fit the payload, and match it with --padding none",
));
}
Ok(size)
}
pub fn validate(&self) -> io::Result<()> {
if self.count > u16::MAX as u32 + 1 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"count exceeds sequence number range",
));
}
if !self.raw
&& !self.dry_run
&& (self.ping_type.is_some_and(|ty| ty != 8 && ty != 128) || self.code != 0)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"non-echo ICMP type or nonzero code requires --raw",
));
}
if matches!(self.ping_type, Some(8 | 128)) && self.code != 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"echo requests require code 0",
));
}
Ok(())
}
pub fn timeout(&self) -> Duration {
Duration::from_millis(self.timeout_ms)
}
}
pub fn parse_all_arguments() -> Config {
Config::parse()
}
#[cfg(test)]
@ -58,36 +184,65 @@ mod tests {
use super::*;
#[test]
fn parses_existing_options_in_any_order() {
fn parses_binary_payload_and_exact_size() {
let config = Config::try_parse_from([
"rping",
"--raw",
"-s",
"16",
"localhost",
"-p",
"hello",
"-q",
"7",
"127.0.0.1",
"--payload-hex",
"00:ff_01",
"--padding",
"none",
])
.unwrap();
assert!(config.raw_packet);
assert_eq!(config.dest_addr, "localhost");
assert_eq!(config.sequence, 7);
assert_eq!(config.payload_size, 16);
assert_eq!(config.payload_bytes().unwrap(), [0, 255, 1]);
assert_eq!(config.packet_size(3).unwrap(), 11);
}
#[test]
fn rejects_invalid_input_without_panicking() {
for args in [
vec!["rping"],
vec!["rping", "localhost", "--size", "7"],
vec!["rping", "localhost", "--size", "65516"],
vec!["rping", "localhost", "--type", "256"],
vec!["rping", "localhost", "--sequence"],
vec!["rping", "localhost", "--unknown"],
] {
assert!(Config::try_parse_from(args).is_err());
}
fn rejects_invalid_hex_and_mismatched_size() {
let config = Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload-hex",
"0",
"--padding",
"none",
])
.unwrap();
assert!(config.payload_bytes().is_err());
let config = Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload-hex",
"00",
"--padding",
"none",
"--size",
"64",
])
.unwrap();
assert!(config.packet_size(1).is_err());
assert!(
Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload",
"a",
"--payload-hex",
"61"
])
.is_err()
);
}
#[test]
fn custom_code_needs_raw_mode() {
let config =
Config::try_parse_from(["rping", "127.0.0.1", "--type", "3", "--code", "1"]).unwrap();
assert!(config.validate().is_err());
let config =
Config::try_parse_from(["rping", "127.0.0.1", "--type", "3", "--code", "1", "--raw"])
.unwrap();
assert!(config.validate().is_ok());
}
}

View File

@ -1,120 +1,370 @@
use crate::libs::args::Config;
use crate::libs::args::{Config, Family, Output, Padding};
use rand::{RngExt, distr::Alphanumeric};
use socket2::{Domain, Protocol, Socket, Type};
use std::{
io,
net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs, UdpSocket},
thread,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Version {
V4,
V6,
}
impl Version {
fn request_type(self) -> u8 {
match self {
Self::V4 => 8,
Self::V6 => 128,
}
}
fn reply_type(self) -> u8 {
match self {
Self::V4 => 0,
Self::V6 => 129,
}
}
}
pub fn generate_ping_request(config: Config) -> io::Result<()> {
let dest_addr = (config.dest_addr.as_str(), 0)
config.validate()?;
let payload = config.payload_bytes()?;
let size = config.packet_size(payload.len())?;
let destination = if config.dry_run {
// Dry runs do not perform DNS or create sockets. Literal addresses determine the family.
config
.dest_addr
.parse::<IpAddr>()
.ok()
.map(|ip| SocketAddr::new(ip, 0))
} else {
Some(resolve_destination(&config)?)
};
let version = match destination.map(|addr| addr.ip()) {
Some(IpAddr::V4(_)) => Version::V4,
Some(IpAddr::V6(_)) => Version::V6,
None => match config.family {
Family::V6 => Version::V6,
_ => Version::V4,
},
};
if matches!(
(config.family, version),
(Family::V4, Version::V6) | (Family::V6, Version::V4)
) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"destination and --family disagree",
));
}
let ty = config.ping_type.unwrap_or(version.request_type());
if config.code != 0 && ty == version.request_type() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"echo requests require code 0",
));
}
if !config.raw && !config.dry_run && (ty != version.request_type() || config.code != 0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"custom type or code requires --raw",
));
}
let socket = if config.dry_run {
None
} else {
let socket = Socket::new(
match version {
Version::V4 => Domain::IPV4,
Version::V6 => Domain::IPV6,
},
if config.raw { Type::RAW } else { Type::DGRAM },
Some(match version {
Version::V4 => Protocol::ICMPV4,
Version::V6 => Protocol::ICMPV6,
}),
)?;
if let Some(ttl) = config.ttl {
match version {
Version::V4 => socket.set_ttl_v4(u32::from(ttl))?,
Version::V6 => socket.set_unicast_hops_v6(u32::from(ttl))?,
}
}
let bind_addr = match version {
Version::V4 => SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)),
Version::V6 => SocketAddr::from((Ipv6Addr::UNSPECIFIED, 0)),
};
socket.bind(&bind_addr.into())?;
Some(UdpSocket::from(socket))
};
let mut results = Vec::new();
let run_start = Instant::now();
for index in 0..config.count {
if index > 0 && !config.dry_run {
let scheduled =
run_start + Duration::from_millis(config.interval_ms).saturating_mul(index);
if let Some(delay) = scheduled.checked_duration_since(Instant::now()) {
thread::sleep(delay);
}
}
let seq = config.sequence.wrapping_add(index as u16);
let packet = create_buffer(
ty,
config.code,
config.identifier,
seq,
&payload,
size,
config.padding,
version,
)?;
let result = if let (Some(socket), Some(destination)) = (&socket, destination) {
probe(socket, destination, &packet, seq, &config, version)?
} else {
ProbeResult::DryRun
};
render_probe(&config, index, seq, &packet, &result);
results.push(result);
}
render_summary(&config, &results);
if results
.iter()
.all(|r| matches!(r, ProbeResult::Echo { .. } | ProbeResult::DryRun))
{
Ok(())
} else {
Err(io::Error::other(
"one or more probes did not receive a matching reply",
))
}
}
fn resolve_destination(config: &Config) -> io::Result<SocketAddr> {
(config.dest_addr.as_str(), 0)
.to_socket_addrs()?
.find(SocketAddr::is_ipv4)
.find(|addr| match config.family {
Family::Auto => true,
Family::V4 => addr.is_ipv4(),
Family::V6 => addr.is_ipv6(),
})
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"destination has no IPv4 address",
"destination has no address in the requested family",
)
})?;
let (buffer, checksum) = create_buffer(
config.ping_type,
config.identifier,
config.sequence,
config.payload.as_deref().unwrap_or_default().as_bytes(),
config.payload_size,
)?;
let socket = Socket::new(
Domain::IPV4,
if config.raw_packet {
Type::RAW
} else {
Type::DGRAM
},
Some(Protocol::ICMPV4),
)?;
// The kernel supplies the IPv4 header, including in raw mode.
socket.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)).into())?;
socket.set_read_timeout(Some(Duration::from_secs(1)))?;
// Transfer ownership instead of creating two owners of the same descriptor.
let socket: UdpSocket = socket.into();
print_send_pre_message(checksum, &buffer);
let now = Instant::now();
let bytes = socket.send_to(&buffer, dest_addr)?;
print_send_post_messages(bytes, dest_addr, checksum);
})
}
enum ProbeResult {
DryRun,
Echo {
source: IpAddr,
bytes: usize,
elapsed: Duration,
response: Vec<u8>,
},
Error {
source: IpAddr,
ty: u8,
code: u8,
response: Vec<u8>,
},
Timeout,
}
fn probe(
socket: &UdpSocket,
destination: SocketAddr,
packet: &[u8],
seq: u16,
config: &Config,
version: Version,
) -> io::Result<ProbeResult> {
let start = Instant::now();
let sent = socket.send_to(packet, destination)?;
if sent != packet.len() {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"partial ICMP packet send",
));
}
let expected_id = if config.raw {
config.identifier
} else {
socket.local_addr()?.port()
};
let deadline = start + config.timeout();
let mut buf = vec![0; 65535];
loop {
let remaining = Duration::from_secs(1)
.checked_sub(now.elapsed())
.filter(|duration| !duration.is_zero())
.ok_or_else(|| {
io::Error::new(io::ErrorKind::TimedOut, "no response from destination")
})?;
let Some(remaining) = deadline
.checked_duration_since(Instant::now())
.filter(|d| !d.is_zero())
else {
return Ok(ProbeResult::Timeout);
};
socket.set_read_timeout(Some(remaining))?;
let (bytes_recv, source) = socket.recv_from(&mut buf)?;
let packet = received_icmp(&buf[..bytes_recv], config.raw_packet)?;
// Raw sockets also receive the outgoing echo request on loopback.
if config.raw_packet && packet[0] == 8 {
let (length, source) = match socket.recv_from(&mut buf) {
Ok(value) => value,
Err(e)
if matches!(
e.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
) =>
{
return Ok(ProbeResult::Timeout);
}
Err(e) => return Err(e),
};
let Some(icmp) = received_icmp(&buf[..length], config.raw && version == Version::V4) else {
continue;
};
match classify_response(
icmp,
source.ip(),
destination.ip(),
expected_id,
seq,
&packet[8..],
version,
) {
Response::Ignore => continue,
Response::Echo => {
return Ok(ProbeResult::Echo {
source: source.ip(),
bytes: icmp.len(),
elapsed: start.elapsed(),
response: icmp.to_vec(),
});
}
Response::Error(ty, code) => {
return Ok(ProbeResult::Error {
source: source.ip(),
ty,
code,
response: icmp.to_vec(),
});
}
}
if source.ip() != dest_addr.ip() {
continue;
}
print_recv_post_message(packet, packet.len(), now.elapsed());
return Ok(());
}
}
fn received_icmp(packet: &[u8], raw: bool) -> io::Result<&[u8]> {
let invalid = || {
io::Error::new(
io::ErrorKind::InvalidData,
"truncated or invalid ICMP response",
)
};
let packet = if raw {
let first = *packet.first().ok_or_else(invalid)?;
let header_len = usize::from(first & 0x0f) * 4;
if first >> 4 != 4 || header_len < 20 {
return Err(invalid());
}
packet.get(header_len..).ok_or_else(invalid)?
} else {
packet
};
fn received_icmp(packet: &[u8], raw_ipv4: bool) -> Option<&[u8]> {
if !raw_ipv4 {
return (packet.len() >= 8).then_some(packet);
}
let first = *packet.first()?;
let header_len = usize::from(first & 0x0f) * 4;
if first >> 4 != 4 || header_len < 20 || packet.len() < header_len + 8 {
return None;
}
Some(&packet[header_len..])
}
enum Response {
Ignore,
Echo,
Error(u8, u8),
}
fn classify_response(
packet: &[u8],
source: IpAddr,
destination: IpAddr,
id: u16,
seq: u16,
sent_payload: &[u8],
version: Version,
) -> Response {
if packet.len() < 8 {
return Err(invalid());
return Response::Ignore;
}
Ok(packet)
let ty = packet[0];
let code = packet[1];
let checksum_ok = version == Version::V6 || calculate_checksum(packet) == 0;
if ty == version.reply_type()
&& code == 0
&& source == destination
&& packet[4..6] == id.to_be_bytes()
&& packet[6..8] == seq.to_be_bytes()
&& packet[8..] == *sent_payload
&& checksum_ok
{
return Response::Echo;
}
let is_error = match version {
Version::V4 => matches!(ty, 3 | 11 | 12),
Version::V6 => matches!(ty, 1..=4),
};
if is_error && checksum_ok && quoted_probe_matches(&packet[8..], destination, id, seq, version)
{
return Response::Error(ty, code);
}
Response::Ignore
}
fn quoted_probe_matches(
quoted: &[u8],
destination: IpAddr,
id: u16,
seq: u16,
version: Version,
) -> bool {
let embedded = match (version, destination) {
(Version::V4, IpAddr::V4(ip)) if quoted.len() >= 28 && quoted[16..20] == ip.octets() => {
received_icmp(quoted, true)
}
(Version::V6, IpAddr::V6(ip))
if quoted.len() >= 48 && quoted[0] >> 4 == 6 && quoted[24..40] == ip.octets() =>
{
Some(&quoted[40..])
}
_ => None,
};
embedded.is_some_and(|p| {
p.len() >= 8
&& p[0] == version.request_type()
&& p[4..6] == id.to_be_bytes()
&& p[6..8] == seq.to_be_bytes()
})
}
#[allow(clippy::too_many_arguments)]
fn create_buffer(
ping_type: u8,
identifier: u16,
sequence: u16,
ty: u8,
code: u8,
id: u16,
seq: u16,
payload: &[u8],
size: usize,
) -> io::Result<(Vec<u8>, u16)> {
padding: Padding,
version: Version,
) -> io::Result<Vec<u8>> {
if !(8..=65515).contains(&size) || payload.len() > size - 8 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"packet size must be 8..=65515 and fit the header and payload",
"invalid packet size",
));
}
let mut buf = vec![0; size];
buf[0] = ping_type;
buf[4..6].copy_from_slice(&identifier.to_be_bytes());
buf[6..8].copy_from_slice(&sequence.to_be_bytes());
if payload.is_empty() {
for byte in &mut buf[8..] {
buf[0] = ty;
buf[1] = code;
buf[4..6].copy_from_slice(&id.to_be_bytes());
buf[6..8].copy_from_slice(&seq.to_be_bytes());
buf[8..8 + payload.len()].copy_from_slice(payload);
if matches!(padding, Padding::Random)
|| (matches!(padding, Padding::Auto) && payload.is_empty())
{
for byte in &mut buf[8 + payload.len()..] {
*byte = rand::rng().sample(Alphanumeric);
}
} else {
buf[8..8 + payload.len()].copy_from_slice(payload);
}
let checksum = calculate_checksum(&buf);
buf[2..4].copy_from_slice(&checksum.to_be_bytes());
Ok((buf, checksum))
if version == Version::V4 {
let checksum = calculate_checksum(&buf);
buf[2..4].copy_from_slice(&checksum.to_be_bytes());
}
// Linux ICMPv6 sockets calculate the mandatory pseudo-header checksum.
Ok(buf)
}
fn calculate_checksum(buf: &[u8]) -> u16 {
@ -127,100 +377,283 @@ fn calculate_checksum(buf: &[u8]) -> u16 {
}
!(sum as u16)
}
fn print_send_pre_message(_checksum: u16, buffer: &[u8]) {
println!("[SENDING ICMP DATA]\n");
println!(" TY C0 CHECK ID SQ PAYLOAD----------> ");
println!(
"{}",
rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(buffer)
);
fn hex_bytes(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn print_send_post_messages(bytes: usize, dest_addr: std::net::SocketAddr, checksum: u16) {
println!(
" > Checksum [{:02x} {:02x}] - {} bytes sent to {}",
(checksum & 0xff00) >> 8,
(checksum) & 0xff,
bytes,
dest_addr
);
fn json_string(value: &str) -> String {
let mut out = String::from("\"");
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c <= '\u{001f}' => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
fn print_recv_post_message(buf: &[u8], bytes_recv: usize, elapsed: Duration) {
// Parse the response from the destination.
let icmp_type = buf[0];
let icmp_code = buf[1];
let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16);
let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16);
let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16);
//let data = &buf[8..bytes_recv];
// Print the parsed response.
println!("\n[RECEIVING ICMP DATA] \n");
println!(" TY C0 CHECK ID SQ PAYLOAD----------> ");
// println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff);
println!(
"{}",
rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(buf)
);
println!(
" > Checksum [{:02x} {:02x}] - \
{} bytes recv over the socket in {:.2} milliseconds",
(icmp_checksum) >> 8,
(icmp_checksum) & 0xff,
bytes_recv,
(elapsed.as_micros() as f64) / 1000.
);
println!(
" > icmp_type = {:width$} icmp_code = {:width$}",
icmp_type,
icmp_code,
width = 2
);
println!(
" > icmp_id = {:width$} icmp_seq = {:width$}",
icmp_id,
icmp_seq,
width = 2
);
println!();
fn render_probe(config: &Config, index: u32, seq: u16, packet: &[u8], result: &ProbeResult) {
match config.output {
Output::Summary => println!("{}", probe_line(index, seq, result)),
Output::Hex => {
println!("[PROBE {}] sequence {}", index + 1, seq);
println!(
"{}",
rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(packet)
);
match result {
ProbeResult::Echo { response, .. } | ProbeResult::Error { response, .. } => {
println!(
"{}",
rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(response)
)
}
_ => {}
}
println!("{}", probe_line(index, seq, result));
}
Output::Json => {
let (status, source, elapsed, response, error) = match result {
ProbeResult::DryRun => ("dry_run", None, None, None, None),
ProbeResult::Timeout => ("timeout", None, None, None, None),
ProbeResult::Echo {
source,
elapsed,
response,
..
} => (
"reply",
Some(source.to_string()),
Some(elapsed.as_secs_f64() * 1000.0),
Some(hex_bytes(response)),
None,
),
ProbeResult::Error {
source,
ty,
code,
response,
} => (
"icmp_error",
Some(source.to_string()),
None,
Some(hex_bytes(response)),
Some((*ty, *code)),
),
};
println!(
"{{\"kind\":\"probe\",\"index\":{},\"sequence\":{},\"status\":{},\"destination\":{},\"source\":{},\"elapsed_ms\":{},\"sent_hex\":{},\"received_hex\":{},\"icmp_type\":{},\"icmp_code\":{}}}",
index + 1,
seq,
json_string(status),
json_string(&config.dest_addr),
source
.as_deref()
.map(json_string)
.unwrap_or_else(|| "null".into()),
elapsed
.map(|ms| ms.to_string())
.unwrap_or_else(|| "null".into()),
json_string(&hex_bytes(packet)),
response
.as_deref()
.map(json_string)
.unwrap_or_else(|| "null".into()),
error
.map(|e| e.0.to_string())
.unwrap_or_else(|| "null".into()),
error
.map(|e| e.1.to_string())
.unwrap_or_else(|| "null".into())
);
}
}
}
fn probe_line(index: u32, seq: u16, result: &ProbeResult) -> String {
match result {
ProbeResult::DryRun => format!("probe {} seq={} dry run", index + 1, seq),
ProbeResult::Timeout => format!("probe {} seq={} timed out", index + 1, seq),
ProbeResult::Echo {
source,
bytes,
elapsed,
..
} => format!(
"probe {} seq={} reply from {}: {} bytes in {:.2} ms",
index + 1,
seq,
source,
bytes,
elapsed.as_secs_f64() * 1000.0
),
ProbeResult::Error {
source, ty, code, ..
} => format!(
"probe {} seq={} ICMP error from {}: type {}, code {}",
index + 1,
seq,
source,
ty,
code
),
}
}
fn render_summary(config: &Config, results: &[ProbeResult]) {
let sent = results.len();
let received = results
.iter()
.filter(|r| matches!(r, ProbeResult::Echo { .. }))
.count();
let errors = results
.iter()
.filter(|r| matches!(r, ProbeResult::Error { .. }))
.count();
let dry = results
.iter()
.filter(|r| matches!(r, ProbeResult::DryRun))
.count();
let rtts: Vec<f64> = results
.iter()
.filter_map(|r| {
if let ProbeResult::Echo { elapsed, .. } = r {
Some(elapsed.as_secs_f64() * 1000.0)
} else {
None
}
})
.collect();
let stats = if rtts.is_empty() {
None
} else {
Some((
rtts.iter().copied().fold(f64::INFINITY, f64::min),
rtts.iter().sum::<f64>() / rtts.len() as f64,
rtts.iter().copied().fold(0.0, f64::max),
))
};
match config.output {
Output::Json => println!(
"{{\"kind\":\"summary\",\"sent\":{sent},\"received\":{received},\"errors\":{errors},\"dry_run\":{dry},\"rtt_min_ms\":{},\"rtt_avg_ms\":{},\"rtt_max_ms\":{}}}",
stats
.map(|s| s.0.to_string())
.unwrap_or_else(|| "null".into()),
stats
.map(|s| s.1.to_string())
.unwrap_or_else(|| "null".into()),
stats
.map(|s| s.2.to_string())
.unwrap_or_else(|| "null".into())
),
_ => {
println!("{sent} probes, {received} replies, {errors} ICMP errors, {dry} dry runs");
if let Some((min, avg, max)) = stats {
println!("RTT min/avg/max = {min:.2}/{avg:.2}/{max:.2} ms");
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::IpAddr;
#[test]
fn checksum_uses_network_byte_order_and_handles_odd_lengths() {
fn checksum_and_exact_payload() {
assert_eq!(
calculate_checksum(&[0, 1, 0xf2, 3, 0xf4, 0xf5, 0xf6, 0xf7]),
0x220d
);
assert_eq!(calculate_checksum(&[1, 2, 3]), 0xfbfd);
for size in [8, 9, 64, 65515] {
let (packet, _) = create_buffer(8, 0x1234, 7, &[], size).unwrap();
assert_eq!(packet.len(), size);
assert_eq!(&packet[4..8], &[0x12, 0x34, 0, 7]);
assert_eq!(calculate_checksum(&packet), 0);
}
let packet = create_buffer(
8,
0,
0x1234,
7,
&[0, 0xff, 0x01],
11,
Padding::None,
Version::V4,
)
.unwrap();
assert_eq!(&packet[8..], &[0, 0xff, 0x01]);
assert_eq!(calculate_checksum(&packet), 0);
}
#[test]
fn matches_only_the_sent_reply() {
let destination: IpAddr = "127.0.0.1".parse().unwrap();
let mut reply = create_buffer(0, 0, 4, 9, b"abc", 11, Padding::None, Version::V4).unwrap();
assert!(matches!(
classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V4),
Response::Echo
));
assert!(matches!(
classify_response(&reply, destination, destination, 4, 10, b"abc", Version::V4),
Response::Ignore
));
reply[8] = b'z';
assert!(matches!(
classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V4),
Response::Ignore
));
}
#[test]
fn malformed_raw_header_is_ignored() {
assert!(received_icmp(&[], true).is_none());
assert!(received_icmp(&[0; 7], false).is_none());
}
#[test]
fn payload_is_padded_and_invalid_sizes_are_rejected() {
let (packet, _) = create_buffer(8, 1, 2, b"hello", 16).unwrap();
assert_eq!(&packet[8..], b"hello\0\0\0");
assert!(create_buffer(8, 1, 2, b"hello", 12).is_err());
assert!(create_buffer(8, 1, 2, &[], 7).is_err());
assert!(create_buffer(8, 1, 2, &[], 65516).is_err());
fn recognizes_quoted_probe_in_router_error() {
let destination: IpAddr = "192.0.2.1".parse().unwrap();
let router: IpAddr = "192.0.2.254".parse().unwrap();
let mut error = vec![0u8; 8 + 20 + 8];
error[0] = 3;
error[8] = 0x45;
error[8 + 16..8 + 20].copy_from_slice(&[192, 0, 2, 1]);
error[28] = 8;
error[32..34].copy_from_slice(&4u16.to_be_bytes());
error[34..36].copy_from_slice(&9u16.to_be_bytes());
let checksum = calculate_checksum(&error);
error[2..4].copy_from_slice(&checksum.to_be_bytes());
assert!(matches!(
classify_response(&error, router, destination, 4, 9, &[], Version::V4),
Response::Error(3, 0)
));
assert!(matches!(
classify_response(&error, router, destination, 4, 10, &[], Version::V4),
Response::Ignore
));
}
#[test]
fn raw_responses_skip_ipv4_header_and_reject_truncation() {
let mut packet = vec![0; 32];
packet[0] = 0x46;
assert_eq!(received_icmp(&packet, true).unwrap().len(), 8);
assert!(received_icmp(&packet[..31], true).is_err());
assert!(received_icmp(&[], true).is_err());
assert!(received_icmp(&[0; 7], false).is_err());
fn ipv6_reply_and_quoted_error_match() {
let destination: IpAddr = "2001:db8::1".parse().unwrap();
let router: IpAddr = "2001:db8::ff".parse().unwrap();
let reply = create_buffer(129, 0, 4, 9, b"abc", 11, Padding::None, Version::V6).unwrap();
assert!(matches!(
classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V6),
Response::Echo
));
assert!(matches!(
classify_response(&reply, router, destination, 4, 9, b"abc", Version::V6),
Response::Ignore
));
let mut error = vec![0u8; 8 + 40 + 8];
error[0] = 1;
error[8] = 0x60;
error[8 + 24..8 + 40].copy_from_slice(&match destination {
IpAddr::V6(ip) => ip.octets(),
_ => unreachable!(),
});
error[48] = 128;
error[52..54].copy_from_slice(&4u16.to_be_bytes());
error[54..56].copy_from_slice(&9u16.to_be_bytes());
assert!(matches!(
classify_response(&error, router, destination, 4, 9, b"abc", Version::V6),
Response::Error(1, 0)
));
}
}