NetworkInspector.Sources.Live 0.24.0

dotnet add package NetworkInspector.Sources.Live --version 0.24.0
                    
NuGet\Install-Package NetworkInspector.Sources.Live -Version 0.24.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetworkInspector.Sources.Live" Version="0.24.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetworkInspector.Sources.Live" Version="0.24.0" />
                    
Directory.Packages.props
<PackageReference Include="NetworkInspector.Sources.Live" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetworkInspector.Sources.Live --version 0.24.0
                    
#r "nuget: NetworkInspector.Sources.Live, 0.24.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NetworkInspector.Sources.Live@0.24.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetworkInspector.Sources.Live&version=0.24.0
                    
Install as a Cake Addin
#tool nuget:?package=NetworkInspector.Sources.Live&version=0.24.0
                    
Install as a Cake Tool

NetworkInspector.Sources.Live

NuGet Downloads .NET 10 License: MIT

Capture live network frames from local operating-system interfaces on Windows (Npcap), Linux (libpcap), and macOS (libpcap) with zero third-party NuGet dependencies. LiveSource implements IFrameSource and IErrorTolerantFrameSource, producing the same Frame values as file readers for Stack, Exporters, Sessions, and the ni command-line tool while keeping all captured traffic and adapter metadata strictly on the local machine.

Highlights

  • Cross-platform with zero third-party packages. Uses .NET NativeLibrary and unmanaged function pointers to call host-installed Npcap (Windows x64/ARM64) or libpcap (Linux and macOS x64/ARM64), referencing only NetworkInspector.Core.
  • All-interfaces capture ("any") with tapered kernel buffers. LiveSource.TryOpen("any", ...) captures across every operational and loopback local interface on Windows, Linux, and macOS (using native "any" when exposed by the OS runtime, or non-blocking multi-handle fan-in with per-interface FrameInterfaceId and LinkType), tapering per-handle kernel ring buffers via 64-bit $\lfloor (2 \times B)/(N+1) \rfloor$ so aggregate kernel memory stays strictly below $2B$ and allocating 0 slab bytes for silent interfaces.
  • Predictable overload behavior. Relies on the OS kernel capture ring buffer (live.kernelBufferSize, default 64 MiB) with O(1) kernel tail-drop and lock-free 64-bit monotonic KernelDroppedFrameCount and InterfaceDroppedFrameCount counters — no unbounded managed queue and no OutOfMemoryException under packet floods. Packets longer than live.snapLength arrive cut to their prefix and are counted in TruncatedFrameCount; the first cut of a capture raises FrameSkipped with the limit's hit sentence. ni warns on stderr after a run when any of the three counts is above zero.
  • Zero per-frame array allocations. Frames up to FrameSlabSize / 4 (16 KiB at the default 64 KiB slab) bump-allocate inside uninitialized shared slabs (0 per-frame byte[] allocations on the NextFrame hot path).
  • Deterministic cross-OS interface discovery. Correlates pcap_findalldevs with .NET NetworkInterface friendly names, MAC addresses, IPv4/IPv6 addresses, and link speeds, strips control characters, and produces shell-safe, brace-free Selector values on Windows (\Device\NPF_{GUID} → bare uppercase GUID).
  • Kernel BPF pre-filtering. Compiles LiveSourceOptions.CaptureFilter with pcap_compile directly in the kernel before frames cross into user space, rejecting syntax errors with LiveCaptureErrorCode.InvalidFilter.
  • Lossless link types and PCAPNG metadata. Translates OS-divergent DLT_* codes (DLT_RAW → LinkType.Raw 101) and preserves if.snap_length, if.raw_link_type, if.os, if.filter, if.hardware, and if.speed through PcapngExporter.
  • Strict local-only privacy and isolated testing. Imports zero packet-injection APIs (pcap_sendpacket, pcap_inject) and zero outbound HTTP/socket APIs. Automated builds and dotnet test never open host NICs or capture host or localhost traffic.

Host Prerequisites and Permissions

LiveSource never bundles a kernel driver. It loads the host's installed Npcap or libpcap exclusively from trusted operating-system directories and returns false with LiveCaptureErrorCode.DriverNotInstalled or PermissionDenied when prerequisites are missing.

OS Runtime library probed Least-privilege capture setup How to verify
Windows (x64, ARM64) %SystemRoot%\System32\Npcap\wpcap.dll, then wpcap.dll with DllImportSearchPath.System32 (never CWD) Install Npcap. Standard mode allows local users; admin-only mode requires an elevated shell sc query npcap or ni interfaces list
Linux (x64, ARM64) libpcap.so.1, libpcap.so.0.8, libpcap.so via SafeDirectories Install libpcap (sudo apt-get install libpcap0.8, sudo dnf install libpcap, or apk add libpcap) and grant sudo setcap cap_net_raw,cap_net_admin=eip /path/to/host-binary getcap /path/to/host-binary or ni interfaces list
macOS (x64, ARM64) /usr/lib/libpcap.A.dylib, libpcap.A.dylib, libpcap.dylib via SafeDirectories System libpcap is pre-installed; grant /dev/bpf* read access via Wireshark's ChmodBPF daemon (access_bpf group) instead of sudo ls -l /dev/bpf0 or ni interfaces list

Install

dotnet add package NetworkInspector.Sources.Live

Add dissectors, sessions, file sources (CachedFrameSource), or exporters as needed:

dotnet add package NetworkInspector.Protocols
dotnet add package NetworkInspector.Sources
dotnet add package NetworkInspector.Sessions
dotnet add package NetworkInspector.Exporters

Quick Start

1. Check Availability and List Interfaces

using NetworkInspector.Sources.Live;

if (!LiveSource.IsAvailable(out string? unavailableReason))
{
    Console.Error.WriteLine(unavailableReason);
    return;
}

if (!LiveSource.TryListInterfaces(out IReadOnlyList<LiveInterfaceInfo>? interfaces, out LiveCaptureError? error))
{
    Console.Error.WriteLine($"{error.Value.Code}: {error.Value.Message}");
    return;
}

foreach (LiveInterfaceInfo nic in interfaces)
{
    string state = nic.IsUp ? "Up" : "Down";
    string ips = string.Join(", ", nic.Addresses);
    Console.WriteLine($"{nic.Selector} | {nic.UiName} | {state} | Loopback={nic.IsLoopback} | MAC={nic.MacAddress} | {ips}");
}

2. Capture Raw Frames

using NetworkInspector.Core;
using NetworkInspector.Sources.Live;

LiveSourceOptions options = new()
{
    CaptureFilter = "udp and port 53",
    MaxDuration = TimeSpan.FromSeconds(5),
};
if (!LiveSource.TryOpen("eth0", out LiveSource? source, out LiveCaptureError? error, options))
{
    Console.Error.WriteLine($"{error.Value.Code}: {error.Value.Message}");
    return;
}

using (source)
{
    FrameInterfaceRegistry registry = new();
    source.Start(registry.RegisterSource(source), registry);
    while (source.NextFrame(cancellationToken) is { } frame)
    {
        Console.WriteLine($"{frame.Timestamp} {frame.LinkType} {frame.Length} bytes");
    }

    Console.WriteLine($"Read={source.ReadFrameCount} KernelDrops={source.KernelDroppedFrameCount} IfDrops={source.InterfaceDroppedFrameCount}");
}

3. Capture and Parse Packets with Stack

using NetworkInspector.Core;
using NetworkInspector.Core.Ids;
using NetworkInspector.Protocols;
using NetworkInspector.Settings;
using NetworkInspector.Sources.Live;

FrameInterfaceRegistry registry = new();
StackBuilder builder = new(new SettingsManager(), registry);
builder.RegisterStandardProtocols();
using Stack stack = builder.Build();

if (!LiveSource.TryOpen("eth0", out LiveSource? source, out LiveCaptureError? error, new LiveSourceOptions { MaxFrames = 100 }))
{
    Console.Error.WriteLine($"{error.Value.Code}: {error.Value.Message}");
    return;
}

using (source)
{
    source.Start(registry.RegisterSource(source), registry);
    ParseOptions parseOptions = new();
    int nextId = 0;

    while (source.NextFrame() is { } frame)
    {
        if (Packet.TryParse(new PacketId(nextId), stack, frame, in parseOptions, out Packet? packet, out _) && packet is not null)
        {
            nextId++;
            Console.WriteLine($"#{packet.Id.Value} {frame.Timestamp} {packet.Info}");
        }
    }
}

4. Live Capture in a Multi-Threaded Session (with Optional Disk Spill)

LiveSource is forward-only (IFrameSource), while Session listeners and views re-read packets by ID (IRandomAccessFrameSource). Wrap LiveSource in CachedFrameSource from NetworkInspector.Sources — use RAM-only caching for short captures (frames.maxCachedPayload, default 4 GiB) or enable EnableDiskSpill = true for long live captures bounded by cache.memoryBudget (RAM working set) and cache.maxSpillSize (disk spill ceiling):

using NetworkInspector.Core;
using NetworkInspector.Protocols;
using NetworkInspector.Sessions;
using NetworkInspector.Sessions.Listeners;
using NetworkInspector.Settings;
using NetworkInspector.Sources.Cached;
using NetworkInspector.Sources.Live;

FrameInterfaceRegistry registry = new();
StackBuilder builder = new(new SettingsManager(), registry);
builder.RegisterStandardProtocols();
using Stack stack = builder.Build();
using Session session = new(stack);

if (!LiveSource.TryOpen("eth0", out LiveSource? liveSource, out LiveCaptureError? error))
{
    Console.Error.WriteLine($"{error.Value.Code}: {error.Value.Message}");
    return;
}

// Session takes ownership of cached once TryAddFrameSource succeeds.
CachedFrameSource cached = new(liveSource, new CachedFrameSourceOptions
{
    EnableDiskSpill = true,
});
if (!session.TryAddFrameSource(cached, out _, out SessionFailure? failure))
{
    cached.Dispose();
    Console.Error.WriteLine(failure?.Message);
    return;
}

if (!session.TryStart(out failure))
{
    Console.Error.WriteLine(failure?.Message);
    return;
}

// Stop live capture from another thread or timer, then wait and shut down cleanly.
liveSource.Stop();
session.WaitForCompletion();
session.Shutdown();

5. Capture Across All Local Interfaces ("any")

using NetworkInspector.Core;
using NetworkInspector.Sources.Live;

if (!LiveSource.TryOpen("any", out LiveSource? source, out LiveCaptureError? error, new LiveSourceOptions { MaxFrames = 100 }))
{
    Console.Error.WriteLine($"{error.Value.Code}: {error.Value.Message}");
    return;
}

using (source)
{
    FrameInterfaceRegistry registry = new();
    source.Start(registry.RegisterSource(source), registry);
    while (source.NextFrame() is { } frame)
    {
        Console.WriteLine($"if={frame.InterfaceId.Value} link={frame.LinkType} len={frame.Length}");
    }
}

Selecting an Interface

Each discovered LiveInterfaceInfo exposes DeviceName, Selector, UiName, Description, MacAddress, Addresses, IsLoopback, IsUp, and SpeedBitsPerSecond.

LiveSource.TryOpen(string interfaceSelector, ...) resolves interfaceSelector in deterministic priority order:

  1. Exact DeviceName — ordinal on Linux/macOS (eth0, en0, lo, or a native Linux any pseudo-device), case-insensitive on Windows (\Device\NPF_{GUID}).
  2. Windows adapter GUID — matches either bare 4B5C8E2A-9D1E-4F3B-8C7A-1A2B3C4D5E6F or braced {4B5C8E2A-9D1E-4F3B-8C7A-1A2B3C4D5E6F}.
  3. Exact Selector — case-insensitive match against LiveInterfaceInfo.Selector. On Windows NPF GUID paths, Selector is the uppercase bare GUID without {} braces because ni CLI source specifications forbid shell metacharacters ({ and }).
  4. Friendly UiName — exact ordinal match first, then case-insensitive ("Wi-Fi" or "wi-fi"). If two or more adapters share the same UiName, resolution refuses with LiveCaptureErrorCode.AmbiguousInterface listing every candidate Selector.
  5. All available interfaces ("any") — case-insensitive wildcard when steps 1–4 matched no single device literally named "any": opens every discovered adapter that is operational or loopback (IsUp || IsLoopback), skipping down or non-activatable adapters with sanitized warnings while at least one interface opens, and registering each opened adapter in FrameInterfaceRegistry with its own FrameInterfaceId and LinkType.

Options Reference

LiveSourceOptions property CLI live: option Default · range Behavior
(argument to TryOpen) interface required OS device name, brace-free Windows GUID, unique UiName, or any
UiName uiName interface UiName ("any" for multi-NIC any) Display name override for the source
CaptureFilter filter empty (all traffic) Kernel BPF capture filter expression (pcap_compile)
Promiscuous promiscuous true Requests promiscuous mode when supported by the adapter
ImmediateMode immediate true Delivers packets immediately instead of waiting for ReadTimeout
ReadTimeout readTimeoutMs 10 ms · 1 ms–60 s Bounds idle polling cadence for MaxDuration, cancellation, and drop stats
MaxFrames count 0 (unlimited) · 0..ArrayIndexIdRange.MaxCount Stops cleanly after returning N frames (EstimatedFrameCount = N)
MaxDuration duration null (unlimited) · > 0 Stops cleanly once elapsed wall-clock time since Start reaches the limit
FrameSlabSize frameSlabBytes 65,536 (64 KiB) · 0 or 1 KiB–16 MiB Shared uninitialized payload slab size (0 = one byte[] per frame)
ErrorTolerance errorTolerance Tolerant · tolerant\|strict Tolerant skips malformed/oversized packets and disconnected any slots; Strict stops on first error
SnapLength snapLength 256 KiB · 64 B–16 MiB or off Maximum captured bytes accepted per packet (live.snapLength)
KernelBufferSize kernelBufferSize 64 MiB · 1 MiB–2 GiB - 1 or off OS kernel capture ring-buffer budget (B for 1 handle; $\lfloor (2 \times B)/(N+1) \rfloor$ per handle across $N > 1$ any handles)
MaxFilterLength maxFilterLength 8 KiB · 64 B–1 MiB or off Maximum UTF-8 length of CaptureFilter (live.maxFilterLength)
MaxInterfaces maxInterfaces 4,096 · 1–65,536 or off Maximum host capture interfaces enumerated (live.maxInterfaces)

Kernel BPF Capture Filters vs. Display Filters

LiveSourceOptions.CaptureFilter (CLI live:...,filter=...) is compiled by pcap_compile into kernel BPF bytecode and evaluated before packets leave the OS kernel. Use it to discard bulk irrelevant traffic at wire speed (for example udp and port 53 or host 192.0.2.10). Syntax errors fail immediately at TryOpen with LiveCaptureErrorCode.InvalidFilter.

NetworkInspector.Filter (CLI --filter) evaluates deep dissected protocol fields after Stack parses the frame (for example dns.qry.name contains "example" or someip.service_id == 0x1234). Combine both for best throughput: a coarse kernel BPF filter sheds 95%+ of traffic in kernel space, while the display filter inspects protocol payloads.

Performance, Overload Handling, and Drop Counters

  • Why there is no second managed packet queue. NextFrame copies each captured packet once from the native libpcap/Npcap ring buffer straight into a FrameSlabAllocator slice. Adding a background producer thread and unbounded Channel<Frame> would add extra copies, context switches, and OutOfMemoryException risk during floods.
  • What happens when frames arrive faster than processed. The OS kernel capture ring buffer (live.kernelBufferSize, default 64 MiB) absorbs bursts (~540 ms at 1 Gbps full line rate, ~54 ms at 10 Gbps). When sustained arrival exceeds consumer throughput, the kernel tail-drops newest packets in O(1) before any managed allocation or copy happens.
  • Sizing KernelBufferSize:
Workload Suggested live.kernelBufferSize Notes
Control plane / CAN / low-rate lab 4 MiB–16 MiB Small kernel footprint
1 Gbps bursty traffic (default) 64 MiB Absorbs ~0.5 s of full-rate bursts
10 Gbps bursty traffic 256 MiB–512 MiB Pair with a kernel BPF CaptureFilter
  • Multi-interface "any" kernel buffer tapering. Opening $N$ local interfaces at full $B = 64\text{ MiB}$ each would reserve $N \times B$ of kernel pool for mostly silent virtual/VPN adapters. For $N \ge 1$ candidate handles, LiveSource computes per-handle size in 64-bit integer arithmetic as $B$ when $N = 1$ and $\lfloor (2 \times B)/(N+1) \rfloor$ when $N > 1$ (for example 64 MiB at $N=1$, ~42.6 MiB at $N=2$, 32 MiB at $N=3$, 8 MiB at $N=15$, 4 MiB at $N=31$ — aggregate kernel memory is always strictly below $2B$). If the per-handle share falls below 1 MiB, TryOpen refuses with LiveCaptureErrorCode.LimitExceeded naming live.kernelBufferSize (off passes 2,147,483,647). All handles share one on-demand FrameSlabAllocator, so silent interfaces allocate 0 user-space slab bytes.
  • Reading drop counters. KernelDroppedFrameCount (ps_drop) and InterfaceDroppedFrameCount (ps_ifdrop) are thread-safe 64-bit monotonic counters polled every 1,024 frames, on read timeouts, and on stop/EOF (summed across all opened handles in multi-interface "any" mode). Unsigned 32-bit delta accumulation guarantees monotonicity even past 2^32 drops on long captures.
  • Zero-allocation hot path with frame slabs. At the default FrameSlabSize = 65_536 (64 KiB), sequential frames up to 16 KiB bump-allocate out of uninitialized slabs with 0 per-frame byte[] allocations. Larger frames get dedicated arrays without displacing the active slab. Set FrameSlabSize = 0 if your caller retains sparse individual Frame instances indefinitely without CachedFrameSource.

LiveSource maps OS-dependent DLT_* values returned by pcap_datalink onto platform-independent LinkType values (DLT_EN10MB → LinkType.Ethernet, BSD/Linux DLT_RAW 12/14 → LinkType.Raw 101, DLT_LINUX_SLL2 → 276, DLT_CAN_SOCKETCAN → 227, passing unknown numeric codes through unchanged). Start populates if.snap_length, if.raw_link_type, if.os, if.filter, if.hardware, and if.speed on FrameInterfaceInfo.Properties so PcapngExporter preserves them in PCAPNG Interface Description Blocks. Domain details: docs/domain/live-capture.md.

Error Tolerance and Adapter Disconnects

  • ErrorToleranceMode.Tolerant (default): malformed native headers or packets exceeding live.snapLength raise FrameSkipped (FrameReadErrorKind.MalformedHeader), increment SkippedFrameCount and ErrorCount, and continue.
  • ErrorToleranceMode.Strict: raises FrameSkipped once for the first malformed or oversized packet and returns null.
  • Mid-capture disconnect (PCAP_ERROR when a USB or virtual NIC disappears): on a single-interface source (or in Strict mode), raises FrameSkipped (FrameReadErrorKind.Other) once and terminates capture cleanly (NextFrame returns null thereafter). In multi-interface "any" under Tolerant mode, raises FrameSkipped once for the disconnected adapter, deactivates only that handle, and continues reading frames from remaining active interfaces until the last handle ends.

Trust-Boundary Limits

All four trust-boundary limits live in LiveLimits.All (live.snapLength, live.kernelBufferSize, live.maxFilterLength, live.maxInterfaces), default to finite values sized for an 8-core / 16 GB reference machine, accept off, bind to LiveSourceOptions.LiveLimits, and are exposed via ni settings describe --limits and --set. Full audit register: docs/limits/live.md.

Thread Safety and Disposal

  • Start and NextFrame are single-reader per IFrameSource.
  • IsRunning, ReadFrameCount, SkippedFrameCount, ErrorCount, HasErrors, KernelDroppedFrameCount, InterfaceDroppedFrameCount, Stop(), and ErrorTolerance are safe from any thread.
  • Stop() and CancellationToken wake a blocked pcap_next_ex call through pcap_breakloop inside ReaderGate.
  • Dispose() is idempotent, safe before Start(), waits for active native calls via ReaderGate.Close() before calling pcap_close, and never runs while FrameSkipped callbacks hold ReaderGate (subscribers may safely call Dispose()).

Host Network Privacy & Isolated Testing

The host machine's network (including localhost / loopback traffic and real host adapter lists) is private:

  • Zero egress & read-only native imports: NetworkInspector.Sources.Live references neither System.Net.Http nor System.Net.Sockets and never imports pcap_sendpacket or pcap_inject (verified by AssemblyReferencesTests).
  • Zero host capture during builds and tests: dotnet build, dotnet pack, and dotnet test never open a real OS capture interface (Npcap/libpcap), never capture real host or localhost traffic, and never persist or log real host payloads. All automated tests run 100% in-memory against deterministic IPcapNative and IOsNetworkInterfaceProvider doubles, enforced repository-wide by TestCodeHygieneTests.TestCodeNeverCapturesRealHostNetworkTraffic and LiveTestIsolationTests.

Safe Usage (STRIDE)

  • Spoofing: Adapter names and descriptions come from untrusted USB/virtual drivers; InterfaceSanitizer strips all control characters (including CR, LF, and ANSI ESC) and falls back to "Interface 0".
  • Tampering: Windows native loading strictly probes %SystemRoot%\System32\Npcap\wpcap.dll and DllImportSearchPath.System32, never the current working directory (blocking CWE-427 DLL planting). Native packet headers are decoded at exact OS ABI offsets without reading macOS padding bytes.
  • Repudiation: Interface metadata (if.snap_length, if.filter, if.os, if.raw_link_type) and drop counters (KernelDroppedFrameCount, InterfaceDroppedFrameCount) make capture fidelity auditable.
  • Information disclosure: Captured packets and host interface metadata never leave the local process unless your application explicitly writes them to a file. Protect saved captures like the network traffic they contain.
  • Denial of service: Bounded by live.snapLength, live.kernelBufferSize, live.maxFilterLength, and live.maxInterfaces, with O(1) kernel tail-drop under floods instead of managed heap growth.
  • Elevation of privilege: Run with least-privilege OS capture rights (cap_net_raw,cap_net_admin=eip on Linux, ChmodBPF on macOS, or standard Npcap on Windows) rather than running the full application as root / SYSTEM.

Learn More

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on NetworkInspector.Sources.Live:

Package Downloads
NetworkInspector.BuiltInPlugins

Built-in plugins of the kind networkinspector: standard protocols, file, random, and live sources, and the nine exporters on the plugin contract.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.24.0 34 12/2/2026