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
<PackageReference Include="NetworkInspector.Sources.Live" Version="0.24.0" />
<PackageVersion Include="NetworkInspector.Sources.Live" Version="0.24.0" />
<PackageReference Include="NetworkInspector.Sources.Live" />
paket add NetworkInspector.Sources.Live --version 0.24.0
#r "nuget: NetworkInspector.Sources.Live, 0.24.0"
#:package NetworkInspector.Sources.Live@0.24.0
#addin nuget:?package=NetworkInspector.Sources.Live&version=0.24.0
#tool nuget:?package=NetworkInspector.Sources.Live&version=0.24.0
NetworkInspector.Sources.Live
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
.NETNativeLibraryand unmanaged function pointers to call host-installedNpcap(Windows x64/ARM64) orlibpcap(Linux and macOS x64/ARM64), referencing onlyNetworkInspector.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-interfaceFrameInterfaceIdandLinkType), 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 allocating0slab bytes for silent interfaces. - Predictable overload behavior. Relies on the OS kernel capture ring buffer (
live.kernelBufferSize, default64 MiB) with O(1) kernel tail-drop and lock-free 64-bit monotonicKernelDroppedFrameCountandInterfaceDroppedFrameCountcounters — no unbounded managed queue and noOutOfMemoryExceptionunder packet floods. Packets longer thanlive.snapLengtharrive cut to their prefix and are counted inTruncatedFrameCount; the first cut of a capture raisesFrameSkippedwith the limit's hit sentence.niwarns 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 KiBat the default64 KiBslab) bump-allocate inside uninitialized shared slabs (0per-framebyte[]allocations on theNextFramehot path). - Deterministic cross-OS interface discovery. Correlates
pcap_findalldevswith .NETNetworkInterfacefriendly names, MAC addresses, IPv4/IPv6 addresses, and link speeds, strips control characters, and produces shell-safe, brace-freeSelectorvalues on Windows (\Device\NPF_{GUID}→ bare uppercase GUID). - Kernel BPF pre-filtering. Compiles
LiveSourceOptions.CaptureFilterwithpcap_compiledirectly in the kernel before frames cross into user space, rejecting syntax errors withLiveCaptureErrorCode.InvalidFilter. - Lossless link types and PCAPNG metadata. Translates OS-divergent
DLT_*codes (DLT_RAW→LinkType.Raw101) and preservesif.snap_length,if.raw_link_type,if.os,if.filter,if.hardware, andif.speedthroughPcapngExporter. - Strict local-only privacy and isolated testing. Imports zero packet-injection APIs (
pcap_sendpacket,pcap_inject) and zero outbound HTTP/socket APIs. Automated builds anddotnet testnever open host NICs or capture host orlocalhosttraffic.
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:
- Exact
DeviceName— ordinal on Linux/macOS (eth0,en0,lo, or a native Linuxanypseudo-device), case-insensitive on Windows (\Device\NPF_{GUID}). - Windows adapter GUID — matches either bare
4B5C8E2A-9D1E-4F3B-8C7A-1A2B3C4D5E6For braced{4B5C8E2A-9D1E-4F3B-8C7A-1A2B3C4D5E6F}. - Exact
Selector— case-insensitive match againstLiveInterfaceInfo.Selector. On Windows NPF GUID paths,Selectoris the uppercase bare GUID without{}braces becauseniCLI source specifications forbid shell metacharacters ({and}). - Friendly
UiName— exact ordinal match first, then case-insensitive ("Wi-Fi"or"wi-fi"). If two or more adapters share the sameUiName, resolution refuses withLiveCaptureErrorCode.AmbiguousInterfacelisting every candidateSelector. - 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 inFrameInterfaceRegistrywith its ownFrameInterfaceIdandLinkType.
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.
NextFramecopies each captured packet once from the nativelibpcap/Npcapring buffer straight into aFrameSlabAllocatorslice. Adding a background producer thread and unboundedChannel<Frame>would add extra copies, context switches, andOutOfMemoryExceptionrisk during floods. - What happens when frames arrive faster than processed. The OS kernel capture ring buffer (
live.kernelBufferSize, default64 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,LiveSourcecomputes 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 example64 MiBat $N=1$,~42.6 MiBat $N=2$,32 MiBat $N=3$,8 MiBat $N=15$,4 MiBat $N=31$ — aggregate kernel memory is always strictly below $2B$). If the per-handle share falls below1 MiB,TryOpenrefuses withLiveCaptureErrorCode.LimitExceedednaminglive.kernelBufferSize(offpasses2,147,483,647). All handles share one on-demandFrameSlabAllocator, so silent interfaces allocate0user-space slab bytes. - Reading drop counters.
KernelDroppedFrameCount(ps_drop) andInterfaceDroppedFrameCount(ps_ifdrop) are thread-safe 64-bit monotonic counters polled every1,024frames, 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 past2^32drops on long captures. - Zero-allocation hot path with frame slabs. At the default
FrameSlabSize = 65_536(64 KiB), sequential frames up to16 KiBbump-allocate out of uninitialized slabs with0per-framebyte[]allocations. Larger frames get dedicated arrays without displacing the active slab. SetFrameSlabSize = 0if your caller retains sparse individualFrameinstances indefinitely withoutCachedFrameSource.
Link Types and PCAPNG Metadata
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 exceedinglive.snapLengthraiseFrameSkipped(FrameReadErrorKind.MalformedHeader), incrementSkippedFrameCountandErrorCount, and continue.ErrorToleranceMode.Strict: raisesFrameSkippedonce for the first malformed or oversized packet and returnsnull.- Mid-capture disconnect (
PCAP_ERRORwhen a USB or virtual NIC disappears): on a single-interface source (or inStrictmode), raisesFrameSkipped(FrameReadErrorKind.Other) once and terminates capture cleanly (NextFramereturnsnullthereafter). In multi-interface"any"underTolerantmode, raisesFrameSkippedonce 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
StartandNextFrameare single-reader perIFrameSource.IsRunning,ReadFrameCount,SkippedFrameCount,ErrorCount,HasErrors,KernelDroppedFrameCount,InterfaceDroppedFrameCount,Stop(), andErrorToleranceare safe from any thread.Stop()andCancellationTokenwake a blockedpcap_next_excall throughpcap_breakloopinsideReaderGate.Dispose()is idempotent, safe beforeStart(), waits for active native calls viaReaderGate.Close()before callingpcap_close, and never runs whileFrameSkippedcallbacks holdReaderGate(subscribers may safely callDispose()).
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.Livereferences neitherSystem.Net.HttpnorSystem.Net.Socketsand never importspcap_sendpacketorpcap_inject(verified byAssemblyReferencesTests). - Zero host capture during builds and tests:
dotnet build,dotnet pack, anddotnet testnever open a real OS capture interface (Npcap/libpcap), never capture real host orlocalhosttraffic, and never persist or log real host payloads. All automated tests run 100% in-memory against deterministicIPcapNativeandIOsNetworkInterfaceProviderdoubles, enforced repository-wide byTestCodeHygieneTests.TestCodeNeverCapturesRealHostNetworkTrafficandLiveTestIsolationTests.
Safe Usage (STRIDE)
- Spoofing: Adapter names and descriptions come from untrusted USB/virtual drivers;
InterfaceSanitizerstrips 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.dllandDllImportSearchPath.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, andlive.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=eipon Linux,ChmodBPFon macOS, or standardNpcapon Windows) rather than running the full application asroot/SYSTEM.
Learn More
- Live capture guide — step-by-step CLI and C# workflows plus troubleshooting matrix
- Live limits register — sizing basis, ranges, and hit behavior
- Live capture domain rules — 3-OS
pcap_pkthdrABI andDLT_*wire facts - Architecture · Decision record
- Sources README · CLI README
License
| Product | Versions 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. |
-
net10.0
- InvariantStringHelper (>= 1.0.0)
- NetworkInspector.Core (>= 0.24.0)
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 |