Expand description
An ICMP echo (“ping”) implementation for IPv4 and IPv6.
Send ICMP echo requests to a target IpAddr and wait for the reply or a
timeout.
§Quick start
For a one off ping, call ping() with a target and a timeout.
use std::net::IpAddr;
use std::time::Duration;
let target: IpAddr = "8.8.8.8".parse().unwrap();
let reply = ping::ping(target, Duration::from_secs(1))?;
println!("rtt {:?} from {}", reply.rtt, reply.source);ping() opens a new socket every time. To ping repeatedly, create a
Pinger and call Pinger::ping instead. The pinger keeps its sockets
open between pings.
use std::net::IpAddr;
use std::time::Duration;
use ping::Pinger;
let target: IpAddr = "8.8.8.8".parse().unwrap();
let mut pinger = Pinger::new();
let reply = pinger.ping(target, Duration::from_secs(1))?;
println!("rtt {:?} from {}", reply.rtt, reply.source);Per request options such as the TTL and the payload are set on a
Request, and socket options such as the socket type are set with
Pinger::builder.
use std::net::IpAddr;
use std::time::Duration;
use ping::{Pinger, Request, SocketType};
let target: IpAddr = "8.8.8.8".parse().unwrap();
let mut pinger = Pinger::builder()
.socket_type(SocketType::RAW)
.build()?;
let request = Request::new(target).ttl(5).payload(b"hello".to_vec());
pinger.ping(request, Duration::from_secs(1))?;§Pinging a host name
Only an IpAddr is accepted. To ping a host name, resolve it first with
ToSocketAddrs.
use std::net::ToSocketAddrs;
use std::time::Duration;
// The port is irrelevant, we only need the resolved IP.
let addr = "www.google.com:0"
.to_socket_addrs()
.unwrap()
.next()
.unwrap()
.ip();
ping::ping(addr, Duration::from_secs(1))?;§Socket types
Sending ICMP traffic over a RAW socket needs elevated
privileges, while a DGRAM socket works unprivileged
on most systems. See SocketType for the default order.
§Tokio
With the tokio feature, ping::tokio::ping and ping::tokio::Pinger
provide the same API with an async ping. Configure an async pinger with
Pinger::builder and build_tokio.
Modules§
- tokio
- Asynchronous pinger for Tokio, available with the
tokiofeature.
Structs§
- Pinger
- Sends ICMP echo requests, reusing its sockets across pings.
- Pinger
Builder - Builder for a
Pingerwith socket level options. - Reply
- A matching echo reply, returned by
Pinger::ping. - Request
- A single echo request sent by
Pinger::ping.
Enums§
- Error
- Errors that can occur while sending a ping or decoding its reply.
- Socket
Type - The kind of socket used to send the ICMP request.
Functions§
- ping
- Sends a single echo request and blocks until the matching reply arrives or
timeoutelapses.