1个不稳定版本
0.1.0 | 2022年5月27日 |
---|
#31 in #流量
每月47次下载
用于 netop
14KB
230 行
语言: 🇺🇸 英语 | 🇨🇳 简体中文
netraffic
概述
netraffic是一个Rust库,提供统计网络流量的能力。
先决条件
Windows
下载WinPcap开发者包。将/Lib
或/Lib/x64
文件夹添加到LIB环境变量中。
Linux
安装libpcap
在基于Debian的Linux上,运行apt install libpcap-dev
Mac OS X
默认情况下,Mac OS X应已安装libpcap。
安装
-
获取最新版本 -> https://crates.io/crates/netraffic
-
添加依赖
[dependencies]
netraffic = "0.1.0"
- 用法
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.add_listener(Filter::new("eth0".to_string(), rule1.to_string()));
traffic.add_listener(Filter::new("eth0".to_string(), rule2.to_string()));
loop {
thread::sleep(Duration::from_millis(1000));
println!(
"rule1: {}, traffic: {:#?} Bytes",
rule1,
traffic.get_data().get(rule1).unwrap().total
);
println!(
"rule2: {}, traffic: {:#?} Bytes",
rule2,
traffic.get_data().get(rule2).unwrap().total
);
}
}
了解更多 示例
商品
文档
流量
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>>
}
过滤器
#[derive(Debug, Clone)]
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/pcap_set_immediate_mode.3pcap.html
pub immediate_mode: bool,
}
/// Init filter, the default immediate_mode = true
Filter::new("eth0".to_string(), "tcp port 80".to_string());
/// or set immediate_mode field
Filter {
device: "eth0".to_string(),
rule: "tcp port 80".to_string(),
immediate_mode: true,
}
快照
#[derive(Debug, Clone, Copy)]
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 all network interface
pub fn get_device() -> Result<Vec<Device>, Error>
获取默认设备
/// Get default network interface
pub fn get_default_device() -> Result<Device, Error>
示例
感谢
依赖
~180–800KB
~12K SLoC