Language : 🇺🇸 English | 🇨🇳 ç®€ä½“ä¸æ–‡
netraffic is a rust library that provides ability to statistics network traffic.
Download the WinPcap Developer's Pack. Add the /Lib
or /Lib/x64
folder to your LIB environment variable.
Install libpcap
On Debian based Linux, apt install libpcap-dev
libpcap should be installed on Mac OS X by default.
Get the latest version -> https://crates.io/crates/netraffic
Add the dependent
toml
[dependencies]
netraffic = "0.1.0"
Usage ```rust use std::{thread, time::Duration}; use netraffic::{Filter, Traffic};
fn main() { let mut traffic = Traffic::new(); // rule look here: https://biot.com/capstats/bpf.html let rule1 = "port 443"; let rule2 = "src host 127.0.0.1"; traffic.addlistener(Filter::new("eth0".tostring(), rule1.tostring())); traffic.addlistener(Filter::new("eth0".tostring(), rule2.tostring())); loop { thread::sleep(Duration::frommillis(1000)); println!( "rule1: {}, traffic: {:#?} Bytes", rule1, traffic.getdata().get(rule1).unwrap().total ); println!( "rule2: {}, traffic: {:#?} Bytes", rule2, traffic.get_data().get(rule2).unwrap().total ); } } ```
Learn More Examples
struct -> Traffic · Filter · Snapshot
mod (device
) -> getdevice · getdefault_device
Traffic
rust
impl Traffic {
/// Init traffic
pub fn new() -> Self
/// Add a new filter to the traffic data center.
pub fn add_listener(&mut self, filter: Filter)
/// Remove a filter from the traffic data center.
pub fn remove_listener(&self, rule: String)
/// Suspend a listener by rule.
pub fn suspend_listener(&self, rule: String)
/// Resume a listener by rule.
pub fn resume_listener(&self, rule: String)
/// Get the traffic snapshot, until Rwlock is free.
pub fn get_data(&self) -> HashMap<String, Snapshot>
/// Try to get the traffic snapshot.
/// if Rwlock is locked, return None.
pub fn try_get_data(&self) -> Option<HashMap<String, Snapshot>>
}
Filter
```rust
pub struct Filter { /// Name of network interface pub device: String, /// Filtering rules /// BPF : https://biot.com/capstats/bpf.html pub rule: String, /// Whether the mode is immediately modeled, the default true /// https://www.tcpdump.org/manpages/pcapsetimmediatemode.3pcap.html pub immediatemode: bool, }
/// Init filter, the default immediatemode = true Filter::new("eth0".tostring(), "tcp port 80".tostring()); /// or set immediatemode field Filter { device: "eth0".tostring(), rule: "tcp port 80".tostring(), immediate_mode: true, } ```
Snapshot
```rust
pub struct Snapshot { /// The total byte after add_listener pub total: u64, /// The latest package of data byte pub len: u64, /// The latest package of data timestamp pub timestamp: u64, } ```
get_device
rust
/// Get all network interface
pub fn get_device() -> Result<Vec<Device>, Error>
get_default_device
rust
/// Get default network interface
pub fn get_default_device() -> Result<Device, Error>
🖥 Get network interface device