| Crates.io | ping |
| lib.rs | ping |
| version | 0.6.1 |
| created_at | 2017-09-17 09:06:32.023444+00 |
| updated_at | 2025-07-01 14:30:52.204354+00 |
| description | Simple and naive ping implementation in Rust. |
| homepage | |
| repository | https://github.com/aisk/rust-ping |
| max_upload_size | |
| id | 32031 |
| size | 35,437 |
Ping function implemented in rust.
To perform a basic ping, you can use the ping::new function to create a Ping instance and then call the send method. By default, on non-Windows systems, it attempts to use a DGRAM socket, falling back to RAW on Windows.
fn main() {
let target_ip = "8.8.8.8".parse().unwrap();
match ping::new(target_ip).send() {
Ok(_) => println!("Ping successful!"),
Err(e) => eprintln!("Ping failed: {}", e),
}
}
You can also configure various options like timeout, TTL, and socket type using the builder pattern:
use std::time::Duration;
fn main() {
let target_ip = "8.8.8.8".parse().unwrap();
match ping::new(target_ip)
.timeout(Duration::from_secs(2))
.ttl(128)
.send()
{
Ok(_) => println!("Ping successful with custom options!"),
Err(e) => eprintln!("Ping failed: {}", e),
}
Sending an ICMP package typically requires creating a raw socket, which often demands special privileges (e.g., running with sudo on Linux). This can introduce security risks.
Modern operating systems support unprivileged ping using dgram sockets, which do not require elevated privileges.
You can specify the socket type using the socket_type method of the Ping builder.
fn main() {
let target_ip = "8.8.8.8".parse().unwrap();
// Using a DGRAM socket (unprivileged)
match ping::new(target_ip).socket_type(ping::DGRAM).send() {
Ok(_) => println!("Ping successful with DGRAM socket!"),
Err(e) => eprintln!("Ping failed with DGRAM socket: {}", e),
}
// Using a RAW socket (may require privileges)
match ping::new(target_ip).socket_type(ping::RAW).send() {
Ok(_) => println!("Ping successful with RAW socket!"),
Err(e) => eprintln!("Ping failed with RAW socket: {}", e),
}
}
For Linux users, even if the kernel supports dgram ping, some distributions (like Arch) might disable it by default. More details: https://wiki.archlinux.org/title/sysctl#Allow_unprivileged_users_to_create_IPPROTO_ICMP_sockets
This library contains codes from https://github.com/knsd/tokio-ping, which is licensed under either of
And other codes is licensed under