single-ping
A simple, lightweight ICMP ping library for Rust that supports both IPv4 and IPv6.
Features
- Support for both IPv4 and IPv6
- Simple API
- Synchronous ping operations
- DNS hostname resolution
- Latency measurement in milliseconds
- Packet validation
Installation
Add this to your Cargo.toml:
[]
= "0.1.1"
Usage
Basic Example
use ping;
Ping a Hostname
use ping;
Check for Dropped Packets
use ping;
API
ping(host: &str, timeout: u64, size: u64) -> Result<PingResult, Box<dyn std::error::Error>>
Sends an ICMP echo request to the specified host.
Parameters:
host- Target host as an IP address or hostname (e.g., "8.8.8.8" or "google.com")timeout- Maximum time to wait for a response, in millisecondssize- Size of the data payload in bytes
Returns:
Ok(PingResult)- Contains information about the ping resultErr(_)- If the host cannot be resolved or network errors occur
PingResult
The result of a ping operation.
Fields:
dropped: bool- Whether the packet was dropped (no response or invalid response)latency_ms: u64- Round-trip time in milliseconds
Requirements
Elevated Privileges
Creating raw ICMP sockets requires elevated privileges:
Linux/macOS:
Or set capabilities on the binary:
Windows: Run your terminal or IDE as Administrator.
Supported Platforms
- Linux
- macOS
- Windows
- Other Unix-like systems
How It Works
- DNS Resolution: The library first resolves the hostname to an IP address (or parses it if already an IP)
- Socket Creation: Creates a raw ICMP socket (ICMPv4 or ICMPv6 based on the resolved address)
- Packet Construction: Builds an ICMP Echo Request packet with the specified payload size
- Send & Receive: Sends the packet and waits for an Echo Reply within the timeout period
- Validation: Validates the received packet to ensure it's a proper Echo Reply
- Latency Calculation: Measures the round-trip time from send to receive
Examples
Run the examples with elevated privileges:
# Basic ping example (if you create one)
# Run tests
Dependencies
socket2- Cross-platform socket operations
License
Apache-2.0
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Troubleshooting
"Permission denied" or "Operation not permitted"
You need to run with elevated privileges (see Requirements).
"Host unreachable" or resolution failures
- Check your network connection
- Verify the hostname is correct
- Ensure DNS resolution is working (
pingcommand works)
IPv6 issues
Some networks may not support IPv6. The library will automatically use IPv4 or IPv6 based on the resolved address.