惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
F
Fortinet All Blogs
B
Blog
GbyAI
GbyAI
P
Proofpoint News Feed
量子位
The Register - Security
The Register - Security
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
B
Blog RSS Feed
WordPress大学
WordPress大学
Recorded Future
Recorded Future
Recent Announcements
Recent Announcements
V
Vulnerabilities – Threatpost
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Secure Thoughts
雷峰网
雷峰网
Stack Overflow Blog
Stack Overflow Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Webroot Blog
Webroot Blog
AWS News Blog
AWS News Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The GitHub Blog
The GitHub Blog
爱范儿
爱范儿
O
OpenAI News
月光博客
月光博客
H
Hacker News: Front Page
S
Security Affairs
W
WeLiveSecurity
The Hacker News
The Hacker News
aimingoo的专栏
aimingoo的专栏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Help Net Security
Help Net Security
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Docker
T
The Blog of Author Tim Ferriss
Spread Privacy
Spread Privacy
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
S
Securelist
Microsoft Azure Blog
Microsoft Azure Blog
TaoSecurity Blog
TaoSecurity Blog
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Packet Parser in Rust: When PCAP Meets Ownership
MournfulCord · 2026-05-13 · via DEV Community

I've been doing packet analysis for a while now. Wireshark is almost always my first port of call when something's wrong on the wire. (Pun intended.) At some point, though, you'll want to go beyond a GUI. You want to write your own tooling, create your own dissection logic, and own the entire pipeline. And that's where Rust comes in.

This post covers how I approached building a packet parser using both the pcap and pnet crates, what each one does, why you need both, and what Rust's ownership model actually means in this context.

Why Rust for Packet Parsing?

The obvious answer is performance. Rust gives you zero-cost abstractions and no garbage collector, which matters when you're parsing high-volume traffic and every microsecond counts.

But honestly, what hooked me was something different: Rust forces you to be explicit about memory, and packet parsing is a domain where sloppiness gets you immediately. A misread offset, a buffer overrun, an assumption about packet length that ends up being wrong, these aren't just bugs alone; they're also common issues that can silently corrupt your analysis or, in a security tool, become vulnerabilities.

Rust’s type system and ownership model don’t let you be anything but constructed and organized. That’s maybe frustrating at first, but it quickly becomes an asset once you learn to work with it.

The Two Crates and Why You Need Both

PCAP: Capturing Packets

The pcap crate is your interface to libpcap. It handles the low-level capture side: opening a device or reading a .pcap file, applying BPF filters, and handing you raw packet data.

use pcap::Capture;

fn main() {
    // Open a live capture on a network interface
    let mut cap = Capture::from_device("eth0")
        .unwrap()
        .promisc(true)
        .snaplen(65535)
        .open()
        .unwrap();

    while let Ok(packet) = cap.next_packet() {
        println!("Captured {} bytes", packet.data.len());
    }
}

Enter fullscreen mode Exit fullscreen mode

What pcap gives you is raw bytes. It doesn't give context on what they mean, because that's not its job. You get a timestamp, length, and a &[u8] slice, then everything else is up to you.

PNET: Dissecting Packets

That's where pnet comes in. The pnet crate provides structured packet dissection across multiple layers: Ethernet, IPv4/IPv6, TCP, UDP, ICMP, and more. It maps your raw byte slice onto typed structs with named fields.

use pnet::packet::ethernet::{EthernetPacket, EtherTypes};
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::tcp::TcpPacket;
use pnet::packet::Packet;

fn dissect(raw: &[u8]) {
    if let Some(eth) = EthernetPacket::new(raw) {
        println!("Src MAC: {}", eth.get_source());
        println!("Dst MAC: {}", eth.get_destination());

        if eth.get_ethertype() == EtherTypes::Ipv4 {
            if let Some(ipv4) = Ipv4Packet::new(eth.payload()) {
                println!("Src IP: {}", ipv4.get_source());
                println!("Dst IP: {}", ipv4.get_destination());
                println!("Protocol: {:?}", ipv4.get_next_level_protocol());
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Notice the "if let Some(...)" pattern throughout. pnet returns Option<T> everywhere; if the byte slice is too short or malformed, you get None. That's basically the API telling you: don't assume the packet is valid just because you received it.

In the field, I've seen plenty of malformed frames. This pattern handles them correctly by design.

Connecting the Two

The typical workflow is: capture with pcap, dissect with pnet. Here's a simple integration:

use pcap::Capture;
use pnet::packet::ethernet::EthernetPacket;
use pnet::packet::Packet;

fn main() {
    let mut cap = Capture::from_device("eth0")
        .unwrap()
        .promisc(true)
        .snaplen(65535)
        .open()
        .unwrap();

    while let Ok(packet) = cap.next_packet() {
        if let Some(eth) = EthernetPacket::new(packet.data) {
            println!(
                "[+] {} -> {} | EtherType: {:?}",
                eth.get_source(),
                eth.get_destination(),
                eth.get_ethertype()
            );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

packet.data is a &[u8]. We pass it directly into EthernetPacket::new(), which borrows it. No copying or allocation required here, only a view into the capture buffer. That's the zero-cost part.

Where Ownership Gets Interesting

Here's something that catches people off guard: pcap's next_packet() returns a packet that borrows from the capture's internal buffer. That means you can't hold onto it past the next loop iteration.

// This won't compile
let mut saved: Option<pcap::Packet> = None;

while let Ok(packet) = cap.next_packet() {
    saved = Some(packet); // Error: lifetime issue
}

Enter fullscreen mode Exit fullscreen mode

Rust is telling you something here: the underlying buffer gets reused. If you want to store packet data, you need to own a copy:

while let Ok(packet) = cap.next_packet() {
    let owned: Vec<u8> = packet.data.to_vec(); // Now you own it
    process(owned);
}

Enter fullscreen mode Exit fullscreen mode

This is a Rust quirk, but it's also a faithful model of how libpcap actually manages its capture buffer. The borrow checker is surfacing behavior that C code would let you get wrong and not bring to your attention.

Reading from a .pcap File

Live capture isn't always what you want. For offline analysis or replay, you can open a saved capture file instead:

let mut cap = Capture::from_file("capture.pcap").unwrap();

while let Ok(packet) = cap.next_packet() {
    // Same dissection logic as live capture
}

Enter fullscreen mode Exit fullscreen mode

The API is identical. All you have to do is swap the source, keep the rest. This is useful for testing your parser on known traffic without needing a live interface, something I do regularly when developing new dissection logic.

Going Deeper: TCP Layer

Once you're past Ethernet and IPv4, getting to TCP is another layer of the same pattern:

use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::tcp::TcpPacket;
use pnet::packet::Packet;

fn parse_tcp(ipv4: &Ipv4Packet) {
    if ipv4.get_next_level_protocol() == IpNextHeaderProtocols::Tcp {
        if let Some(tcp) = TcpPacket::new(ipv4.payload()) {
            println!(
                "TCP {}:{} -> {}:{}  flags: {:08b}",
                ipv4.get_source(),
                tcp.get_source(),
                ipv4.get_destination(),
                tcp.get_destination(),
                tcp.get_flags()
            );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The flags field is a bitmask. You can check individual flags like SYN, ACK, FIN against pnet::packet::tcp::TcpFlags constants, which is where things start getting useful for detecting specific traffic patterns or anomalies.

What This Is Good For

This combination gives you a nice foundation for concepts like:

  • Custom traffic analysis: filter and inspect exactly what you care about, without Wireshark's GUI in your way
  • Telemetry pipelines: feed parsed fields into your own metrics or alerting system
  • Protocol-level diagnostics: spot things like SYN floods, retransmissions, or unusual flag combinations programmatically
  • Field tooling: a single compiled binary you can drop onto any Linux box and run instantly

What's Next

This is the foundation. From here, you can layer in:

  • UDP and ICMP dissection (same pattern, different protocol structs)
  • BPF filters on capture to reduce noise (cap.filter("tcp port 443", true))
  • Writing parsed output to a structured format for further analysis
  • Async capture with tokio for high-throughput environments

I'm building all of this into a simple Rust PCAP tool I've made, and I'll be sharing more of that work in future posts and tutorials.

If you're already working with pcap or pnet, I'd love to hear what you're building! And if you've hit a wall with the borrow checker in this context, ask away. Rust's ownership model looks entirely different once you see it in the context of packet data.