Statistics network traffic --- Rust Library

Overview

Language : 🇺🇸 English | 🇨🇳 简体中文

netraffic

Build Status Crates Downloads Last Commit

Docs GitHub Actions CI LICENSE

Overview

netraffic is a rust library that provides ability to statistics network traffic.

Prerequisites

Windows

Download the WinPcap Developer's Pack. Add the /Lib or /Lib/x64 folder to your LIB environment variable.

Linux

Install libpcap

On Debian based Linux, apt install libpcap-dev

Mac OS X

libpcap should be installed on Mac OS X by default.

Installation

  1. Get the latest version -> https://crates.io/crates/netraffic

  2. Add the dependent

[dependencies]
netraffic = "0.1.0"
  1. Usage
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
        );
    }
}

Learn More Examples

Examples

🖥 Get network interface device

🚥 Statistical traffic

🚄 Calculate network speed

Goods

struct -> Traffic · Filter · Snapshot

mod (device) -> get_device · get_default_device

Documentation

Traffic

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

#[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,
}

Snapshot

#[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_device

/// Get all network interface
pub fn get_device() -> Result<Vec<Device>, Error>

get_default_device

/// Get default network interface
pub fn get_default_device() -> Result<Device, Error>

Thanks

pcap

Comments
  • fix(deps): update rust crate pcap to 0.10.0

    fix(deps): update rust crate pcap to 0.10.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | pcap | dependencies | minor | 0.9.2 -> 0.10.0 |


    Release Notes

    ebfull/pcap

    v0.10.0

    Compare Source

    Added
    • doc will now include all features.
    • Support for sendqueues on Windows.
    • PacketStream::capture_mut to still be able to inject packets when using PacketStream.
    • Capture::iter() that return an iterator that use a codec like Capture::stream().
    • Packet<Dead>::dead_with_precision to enable creating a pcap with nanosecond precision.
    • flags field to Device.
    Changed
    • MSRV is now 1.41.0.
    • PacketStream has been moved from mod stream to the root of the crate.
    • PacketCodec has been moved from mod stream to the root of the crate.
    • PacketCodec::decode() no longer returns a Result.
    • PacketCodec::Type has been renamed to PacketCodec::Item.
    • Device::lookup now returns Result<Option<Device>, Error> rather than Result<Device, Error>. Ok(None) means that the lookup succeeded, but no suitable devices were available. This is consistent with libpcap.
    • Capture and Savefile no longer implement the Sync trait. The underlying libpcap library does not promise thread-safe access for the same capture object from multiple threads.
    • Switched from winapi to windows-sys for Windows builds. windows-sys requires rustc 1.46.0.
    • Capture::next have been rename next_packet to avoid any confusion with Iterator::next.
    Removed
    • mod stream is no longer public.
    • docs-rs feature.
    • full feature.
    • stream::SelectableFd and stream::PacketStream::new as they were only meant to be used internally.

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • chore(deps): update github/codeql-action action to v2

    chore(deps): update github/codeql-action action to v2

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | github/codeql-action | action | major | v1 -> v2 |


    Release Notes

    github/codeql-action

    v2

    Compare Source


    Configuration

    📅 Schedule: At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • chore(deps): update actions-rs/toolchain digest to 88dc235

    chore(deps): update actions-rs/toolchain digest to 88dc235

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | actions-rs/toolchain | action | digest | 16499b5 -> 88dc235 |


    Configuration

    📅 Schedule: At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • chore(deps): update actions/checkout action to v3

    chore(deps): update actions/checkout action to v3

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | actions/checkout | action | major | v2 -> v3 |


    Release Notes

    actions/checkout

    v3

    Compare Source


    Configuration

    📅 Schedule: At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • Cargo.toml (cargo)
    • .github/workflows/publish.yml (github-actions)
    • .github/workflows/test.yml (github-actions)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Enable Renovate Dependency Dashboard creation
    • If semantic commits detected, use semantic commit type fix for dependencies and chore for all others
    • Ignore node_modules, bower_components, vendor and various test/tests directories
    • Autodetect whether to pin dependencies or maintain ranges
    • Rate limit PR creation to a maximum of two per hour
    • Limit to maximum 10 open PRs at any time
    • Group known monorepo packages together
    • Use curated list of recommended non-monorepo package groupings
    • Fix some problems with very old Maven commons versions
    • Ignore spring cloud 1.x releases
    • Ignore web3j 5.0.0 release
    • Ignore http4s digest-based 1.x milestones
    • Use node versioning for @types/node
    • Limit concurrent requests to reduce load on Repology servers until we can fix this properly, see issue 10133
    • Do not upgrade from Alpine stable to edge

    🔡 Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    With your current configuration, Renovate will create 1 Pull Request:

    chore(deps): update actions/checkout action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-checkout-3.x
    • Merge into: main
    • Upgrade actions/checkout to v3

    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • chore(deps): update actions/checkout action to v3

    chore(deps): update actions/checkout action to v3

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | actions/checkout | action | major | v2 -> v3 |


    Release Notes

    actions/checkout

    v3

    Compare Source


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • fix(deps): update rust crate pcap to v1

    fix(deps): update rust crate pcap to v1

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | pcap | dependencies | major | 0.9.2 -> 1.1.0 |


    Release Notes

    rust-pcap/pcap

    v1.1.0

    Compare Source

    Added
    • lending-iter UNSTABLE feature that introduces lending iterator using GATs.
    Changed
    • Examples in the docs have been fixed.

    v1.0.0

    Compare Source

    Changed
    • Public API declared stable.

    v0.11.0

    Compare Source

    Added
    • SendQueue::queue_sg() can add scattered packets, as a slice of std::io::IoSlices, to SendQueues.
    Changed
    • Rename sendqueue::Sync to sendqueue::SendSync to avoid collision with Sync in std's prelude.
    • Build script will fall back to pkg-config if available and LIBPCAP_LIBDIR hasn't been explicitly set.

    v0.10.1

    Compare Source

    Changed
    • MSRV is now 1.46.0.

    v0.10.0

    Compare Source

    Added
    • doc will now include all features.
    • Support for sendqueues on Windows.
    • PacketStream::capture_mut to still be able to inject packets when using PacketStream.
    • Capture::iter() that return an iterator that use a codec like Capture::stream().
    • Packet<Dead>::dead_with_precision to enable creating a pcap with nanosecond precision.
    • flags field to Device.
    Removed
    • BpfProgram no longer have Clone implementation see #​261
    Changed
    • MSRV is now 1.41.0.
    • PacketStream has been moved from mod stream to the root of the crate.
    • PacketCodec has been moved from mod stream to the root of the crate.
    • PacketCodec::decode() no longer returns a Result.
    • PacketCodec::Type has been renamed to PacketCodec::Item.
    • Device::lookup now returns Result<Option<Device>, Error> rather than Result<Device, Error>. Ok(None) means that the lookup succeeded, but no suitable devices were available. This is consistent with libpcap.
    • Capture and Savefile no longer implement the Sync trait. The underlying libpcap library does not promise thread-safe access for the same capture object from multiple threads.
    • Switched from winapi to windows-sys for Windows builds. windows-sys requires rustc 1.46.0.
    • Capture::next have been rename next_packet to avoid any confusion with Iterator::next.
    Removed
    • mod stream is no longer public.
    • docs-rs feature.
    • full feature.
    • stream::SelectableFd and stream::PacketStream::new as they were only meant to be used internally.

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • chore(deps): update actions-rs/toolchain digest to 16499b5

    chore(deps): update actions-rs/toolchain digest to 16499b5

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | actions-rs/toolchain | action | digest | 88dc235 -> 16499b5 |


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • fix(deps): update rust crate pcap to 0.11.0

    fix(deps): update rust crate pcap to 0.11.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | pcap | dependencies | minor | 0.9.2 -> 0.11.0 |


    Release Notes

    rust-pcap/pcap

    v0.11.0

    Compare Source

    Added
    • SendQueue::queue_sg() can add scattered packets, as a slice of std::io::IoSlices, to SendQueues.
    Changed
    • Rename sendqueue::Sync to sendqueue::SendSync to avoid collision with Sync in std's prelude.
    • Build script will fall back to pkg-config if available and LIBPCAP_LIBDIR hasn't been explicitly set.

    v0.10.1

    Compare Source

    Changed
    • MSRV is now 1.46.0.

    v0.10.0

    Compare Source

    Added
    • doc will now include all features.
    • Support for sendqueues on Windows.
    • PacketStream::capture_mut to still be able to inject packets when using PacketStream.
    • Capture::iter() that return an iterator that use a codec like Capture::stream().
    • Packet<Dead>::dead_with_precision to enable creating a pcap with nanosecond precision.
    • flags field to Device.
    Removed
    • BpfProgram no longer have Clone implementation see #​261
    Changed
    • MSRV is now 1.41.0.
    • PacketStream has been moved from mod stream to the root of the crate.
    • PacketCodec has been moved from mod stream to the root of the crate.
    • PacketCodec::decode() no longer returns a Result.
    • PacketCodec::Type has been renamed to PacketCodec::Item.
    • Device::lookup now returns Result<Option<Device>, Error> rather than Result<Device, Error>. Ok(None) means that the lookup succeeded, but no suitable devices were available. This is consistent with libpcap.
    • Capture and Savefile no longer implement the Sync trait. The underlying libpcap library does not promise thread-safe access for the same capture object from multiple threads.
    • Switched from winapi to windows-sys for Windows builds. windows-sys requires rustc 1.46.0.
    • Capture::next have been rename next_packet to avoid any confusion with Iterator::next.
    Removed
    • mod stream is no longer public.
    • docs-rs feature.
    • full feature.
    • stream::SelectableFd and stream::PacketStream::new as they were only meant to be used internally.

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Open

    These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

    Detected dependencies

    cargo
    Cargo.toml
    • pcap 0.9.2
    github-actions
    .github/workflows/publish.yml
    • actions/checkout v3
    • actions-rs/toolchain v1
    .github/workflows/rust-clippy.yml
    • actions/checkout v2
    • actions-rs/toolchain v1@88dc2356392166efad76775c878094f4e83ff746
    • github/codeql-action v2
    .github/workflows/test.yml
    • actions/checkout v3
    • actions/checkout v3

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Owner
勤劳的小蜜蜂
庐山烟雨浙江潮
勤劳的小蜜蜂
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
Rust Imaging Library: A high-level Rust imaging crate.

ril Rust Imaging Library: A performant and high-level Rust imaging crate. Documentation • Crates.io • Discord What's this? This is a Rust crate design

Jay3332 18 Jan 5, 2023
Modern Rust utility library delivering modularity, performance & extras; or simply Rust version of Lodash

Lorust - API Documentation Lorust is the Rust version of Lodash, which is a modern Javascript utilty library delivering modularity, performance & extr

Imamuzzaki Abu Salam 2 Jul 9, 2023
Rust library for hardware accelerated drawing of 2D shapes, images, and text, with an easy to use API.

Speedy2D Hardware-accelerated drawing of shapes, images, and text, with an easy to use API. Speedy2D aims to be: The simplest Rust API for creating a

null 223 Dec 26, 2022
Shuttle is a library for testing concurrent Rust code

Shuttle Shuttle is a library for testing concurrent Rust code. It is an implementation of a number of randomized concurrency testing techniques, inclu

Amazon Web Services - Labs 373 Dec 27, 2022
🦀 In progress Rust library for dogehouse.tv 🦀

dogehouse-rs WARNING: Still work in progress do not use yet Example In Cargo.toml dogehouse-rs = "*" In src/main.rs use dogehouse_rs::prelude::*; use

Will 21 Dec 16, 2021
Comprehensive DSP graph and synthesis library for developing a modular synthesizer in Rust, such as HexoSynth.

HexoDSP - Comprehensive DSP graph and synthesis library for developing a modular synthesizer in Rust, such as HexoSynth. This project contains the com

Weird Constructor 45 Dec 17, 2022
Fluent assertion library for Rust with readable messages.

Assertor Assertor makes test assertions and failure messages more human-readable. Assertor is heavily affected by Java Truth in terms of API design an

Google 20 Dec 12, 2022
Highly experimental, pure-Rust big integer library

grou-num (Pronounced "groo", from the Chiac meaning "big") This package is a highly experimental, unstable big integer library. I would not recommend

Patrick Poitras 1 Dec 18, 2021
"Crates for Cheese" is a Rust collection library of those crates I consider a useful "extended standard".

cfc The purpose of this library is to provide a minimal list of currated crates which enhance the std library. In addition, most or all crates in this

null 0 Dec 23, 2021
An advanced, reactive UI library for Rust

An advanced, reactive UI library for Rust Report a Bug · Request a Feature . Ask a Question What is agui? Agui is an advanced reactive GUI project for

Trevin Miller 28 Nov 26, 2022
Functional Reactive Programming library for Rust

Carboxyl is a library for functional reactive programming in Rust, a functional and composable approach to handle events in interactive applications.

Emilia Bopp 379 Dec 25, 2022
A library for transcoding between bytes in Astro Notation Format and Native Rust data types.

Rust Astro Notation A library for transcoding between hexadecimal strings in Astro Notation Format and Native Rust data types. Usage In your Cargo.tom

Stelar Software 1 Feb 4, 2022
A rust library that provides pseudo-reflection for structs and enums

Treeflection treeflection_derive Treeflection runs a command stored as a string on a tree of structs, collections and primitive types. Commands A comm

Lucas Kent 21 Nov 17, 2022
List public items (public API) of Rust library crates. Enables diffing public API between releases.

cargo wrapper for this library You probably want the cargo wrapper to this library. See https://github.com/Enselic/cargo-public-items. public_items Li

Martin Nordholts 20 Dec 26, 2022
A simple thread schedule and priority library for rust

thread-priority A simple library to control thread schedule policies and thread priority. If your operating system isn't yet supported, please, create

Victor Polevoy 62 Dec 5, 2022
Library for abstract mathematics written by Rust. It is aiming to replace SageMath.

ankolib Roadmap Mathematical Structures Sets Monoids Groups Semirings Rings Algebras Basic Rings and Fields Integers and Rational Numbers Integer Rati

anko 6 Sep 3, 2022
Rust Library for controlling divoom devices that support REST APIs, such as pixoo-64.

Divoom Rust Library for controlling divoom devices that support REST APIs, such as pixoo-64 (and from how divoom's api/doc organizes, maybe more in th

Riff 16 Dec 23, 2022