netflow_parser
A Netflow Parser library for Cisco V5, V7, V9, and IPFIX written in Rust. Supports chaining of multiple versions in the same stream.
Table of Contents
- Example
- Serialization (JSON)
- Filtering for a Specific Version
- Iterator API
- Parsing Out Unneeded Versions
- Error Handling Configuration
- Netflow Common
- Re-Exporting Flows
- Template Cache Configuration
- Custom Enterprise Fields (IPFIX)
- V9/IPFIX Notes
- Performance & Thread Safety
- Features
- Included Examples
Example
V5
use ;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let v5_packet = ;
match default.parse_bytes.first
Want Serialization such as JSON?
Structures fully support serialization. Below is an example using the serde_json macro:
use json;
use NetflowParser;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let v5_packet = ;
println!;
Filtering for a Specific Version
use ;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let v5_packet = ;
let parsed = default.parse_bytes;
let v5_parsed: = parsed.into_iter.filter.collect;
Iterator API
You can use the iterator API to process packets one-by-one as they're parsed instead of returning Vec:
use ;
let buffer = /* your netflow data */;
let mut parser = default;
// Process packets without collecting into a Vec
for packet in parser.iter_packets
The iterator provides access to unconsumed bytes for advanced use cases:
use NetflowParser;
let buffer = /* your netflow data */;
let mut parser = default;
let mut iter = parser.iter_packets;
while let Some = iter.next
// Check if all bytes were consumed
if !iter.is_complete
Benefits of Iterator API
- Zero allocation: Packets are yielded one-by-one without allocating a
Vec - Memory efficient: Ideal for processing large batches or continuous streams
- Lazy evaluation: Only parses packets as you consume them
- Template caching preserved: V9/IPFIX template state is maintained across iterations
- Composable: Works with standard Rust iterator methods (
.filter(),.map(),.take(), etc.) - Buffer inspection: Access unconsumed bytes via
.remaining()and check completion with.is_complete()
Iterator Examples
// Count V5 packets without collecting
let count = parser.iter_packets
.filter
.count;
// Process only the first 10 packets
for packet in parser.iter_packets.take
// Collect only if needed (equivalent to parse_bytes())
let packets: = parser.iter_packets.collect;
// Check unconsumed bytes (useful for mixed protocol streams)
let mut iter = parser.iter_packets;
for packet in &mut iter
if !iter.is_complete
Parsing Out Unneeded Versions
If you only care about a specific version or versions you can specify allowed_versions:
use ;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let v5_packet = ;
let mut parser = default;
parser.allowed_versions = .into;
let parsed = parser.parse_bytes;
This code will return an empty Vec as version 5 is not allowed.
Error Handling Configuration
To prevent memory exhaustion from malformed packets, the parser limits the size of error buffer samples. By default, only the first 256 bytes of unparseable data are stored in error messages. You can customize this limit for all parsers:
use NetflowParser;
let mut parser = default;
// Configure maximum error buffer size for the main parser (default: 256 bytes)
// This applies to generic parsing errors
parser.max_error_sample_size = 512;
// Configure maximum error buffer size for V9 (default: 256 bytes)
parser.v9_parser.max_error_sample_size = 512;
// Configure maximum error buffer size for IPFIX (default: 256 bytes)
parser.ipfix_parser.max_error_sample_size = 512;
let parsed = parser.parse_bytes;
This setting helps prevent memory exhaustion when processing malformed or malicious packets while still providing enough context for debugging.
Netflow Common
We have included a NetflowCommon and NetflowCommonFlowSet structure.
This will allow you to use common fields without unpacking values from specific versions.
If the packet flow does not have the matching field it will simply be left as None.
NetflowCommon and NetflowCommonFlowSet Struct:
use IpAddr;
use ProtocolTypes;
Converting NetflowPacket to NetflowCommon
use ;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let v5_packet = ;
let netflow_common = default
.parse_bytes
.first
.unwrap
.as_netflow_common
.unwrap;
for common_flow in netflow_common.flowsets.iter
Flattened flowsets
To gather all flowsets from all packets into a flattened vector:
use NetflowParser;
let flowsets = default.parse_bytes_as_netflow_common_flowsets;
Custom Field Mappings for V9 and IPFIX
By default, NetflowCommon maps standard IANA fields to the common structure. However, you can customize which fields are used for V9 and IPFIX packets using configuration structs. This is useful when:
- You want to prefer IPv6 addresses over IPv4
- Your vendor uses non-standard field mappings
- You need to extract data from vendor-specific enterprise fields
V9 Custom Field Mapping
use ;
use V9Field;
// Create a custom configuration that prefers IPv6 addresses
let mut config = default;
config.src_addr.primary = Ipv6SrcAddr;
config.src_addr.fallback = Some;
config.dst_addr.primary = Ipv6DstAddr;
config.dst_addr.fallback = Some;
// Use with a parsed V9 packet
// let common = NetflowCommon::from_v9_with_config(&v9_packet, &config);
IPFIX Custom Field Mapping
use ;
use ;
// Create a custom configuration that prefers IPv6 addresses
let mut config = default;
config.src_addr.primary = IANA;
config.src_addr.fallback = Some;
config.dst_addr.primary = IANA;
config.dst_addr.fallback = Some;
// Use with a parsed IPFIX packet
// let common = NetflowCommon::from_ipfix_with_config(&ipfix_packet, &config);
Available Configuration Fields
Both V9FieldMappingConfig and IPFixFieldMappingConfig support configuring:
| Field | Description | Default V9 Field | Default IPFIX Field |
|---|---|---|---|
src_addr |
Source IP address | Ipv4SrcAddr (fallback: Ipv6SrcAddr) | SourceIpv4address (fallback: SourceIpv6address) |
dst_addr |
Destination IP address | Ipv4DstAddr (fallback: Ipv6DstAddr) | DestinationIpv4address (fallback: DestinationIpv6address) |
src_port |
Source port | L4SrcPort | SourceTransportPort |
dst_port |
Destination port | L4DstPort | DestinationTransportPort |
protocol |
Protocol number | Protocol | ProtocolIdentifier |
first_seen |
Flow start time | FirstSwitched | FlowStartSysUpTime |
last_seen |
Flow end time | LastSwitched | FlowEndSysUpTime |
src_mac |
Source MAC address | InSrcMac | SourceMacaddress |
dst_mac |
Destination MAC address | InDstMac | DestinationMacaddress |
Each field mapping has a primary field (always checked first) and an optional fallback field (used if primary is not present in the flow record).
Re-Exporting Flows
Parsed V5, V7, V9, and IPFIX packets can be re-exported back into bytes.
V9/IPFIX Padding Behavior:
- For parsed packets: Original padding is preserved exactly for byte-perfect round-trips
- For manually created packets: Padding is automatically calculated to align FlowSets to 4-byte boundaries
Creating Data Structs:
For convenience, use Data::new() and OptionsData::new() to create data structures without manually specifying padding:
use Data;
// Padding is automatically set to empty vec and calculated during export
let data = new;
See examples/manual_ipfix_creation.rs for a complete example of creating IPFIX packets from scratch.
use ;
// 0000 00 05 00 01 03 00 04 00 05 00 06 07 08 09 00 01 ................
// 0010 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 ................
// 0020 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 ................
// 0030 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 ................
// 0040 00 01 02 03 04 05 06 07 ........
let packet = ;
if let V5 = default
.parse_bytes
.first
.unwrap
Template Cache Configuration
V9 and IPFIX parsers use LRU (Least Recently Used) caching to store templates with a configurable size limit. This prevents memory exhaustion from template flooding attacks while maintaining good performance for legitimate traffic.
Default Behavior
By default, parsers cache up to 1000 templates:
use NetflowParser;
// Uses default cache size of 1000 templates per parser
let parser = default;
Custom Cache Size - Using Builder Pattern (Recommended)
The builder pattern provides an ergonomic way to configure your parser:
use NetflowParser;
use TtlConfig;
// Configure both V9 and IPFIX parsers with the same settings
let parser = builder
.with_cache_size
.build
.expect;
// Configure V9 and IPFIX independently
let parser = builder
.with_v9_cache_size
.with_ipfix_cache_size
.build
.expect;
// Combine cache size with TTL configuration
let parser = builder
.with_cache_size
.with_ttl
.build
.expect;
// Full configuration example
let parser = builder
.with_v9_cache_size
.with_ipfix_cache_size
.with_v9_ttl
.with_ipfix_ttl
.with_allowed_versions
.with_max_error_sample_size
.build
.expect;
Cache Behavior
- When the cache is full, the least recently used template is evicted
- Templates are keyed by template ID (per source)
- Each parser instance maintains its own template cache
- For multi-source deployments, create separate parser instances per source
Template TTL (Time-to-Live)
⚠️ Breaking Change in v0.7.0: Packet-based and combined TTL modes have been removed. Only time-based TTL is now supported. See RELEASES.md for migration guide.
Optionally configure templates to expire after a time duration. This is useful for:
- Handling exporters that reuse template IDs with different schemas
- Forcing periodic template refresh from exporters
- Testing template re-learning behavior
Note: TTL is disabled by default. Templates persist until LRU eviction unless explicitly configured.
Configuration Examples
use NetflowParser;
use TtlConfig;
use Duration;
// Templates expire after 2 hours
let parser = builder
.with_cache_size
.with_ttl
.build
.unwrap;
// Using default TTL (2 hours)
let parser = builder
.with_cache_size
.with_ttl
.build
.unwrap;
// Different TTL for V9 and IPFIX
let parser = builder
.with_v9_ttl
.with_ipfix_ttl
.build
.unwrap;
Template Cache Introspection
You can inspect the template cache state at runtime:
use NetflowParser;
let parser = default;
// Get cache statistics
let v9_stats = parser.v9_cache_stats;
println!;
let ipfix_stats = parser.ipfix_cache_stats;
println!;
// List all cached template IDs
let v9_templates = parser.v9_template_ids;
println!;
let ipfix_templates = parser.ipfix_template_ids;
println!;
// Check if a specific template exists (doesn't affect LRU ordering)
if parser.has_v9_template
// Clear all templates (useful for testing)
let mut parser = default;
parser.clear_v9_templates;
parser.clear_ipfix_templates;
Custom Enterprise Fields (IPFIX)
IPFIX supports vendor-specific enterprise fields that extend the standard IANA field set. The library provides built-in support for several vendors (Cisco, VMWare, Netscaler, etc.), but you can also register your own custom enterprise fields without modifying the library source code.
Registering Custom Enterprise Fields
Use the builder pattern to register enterprise field definitions with your parser:
use NetflowParser;
use FieldDataType;
use EnterpriseFieldDef;
// Define custom enterprise fields for your vendor
let parser = builder
.register_enterprise_field
.register_enterprise_field
.register_enterprise_field
.build
.expect;
// Parse IPFIX packets - custom fields are automatically decoded!
let packets = parser.parse_bytes;
Bulk Registration
You can also register multiple fields at once:
use NetflowParser;
use FieldDataType;
use EnterpriseFieldDef;
let custom_fields = vec!;
let parser = builder
.register_enterprise_fields
.build
.expect;
Available Data Types
When registering enterprise fields, you can use any of the following built-in data types:
FieldDataType::UnsignedDataNumber- Unsigned integers (variable length)FieldDataType::SignedDataNumber- Signed integers (variable length)FieldDataType::Float64- 64-bit floating pointFieldDataType::String- UTF-8 stringsFieldDataType::Ip4Addr- IPv4 addressesFieldDataType::Ip6Addr- IPv6 addressesFieldDataType::MacAddr- MAC addressesFieldDataType::DurationSeconds- Durations in secondsFieldDataType::DurationMillis- Durations in millisecondsFieldDataType::DurationMicrosNTP- NTP microsecond timestampsFieldDataType::DurationNanosNTP- NTP nanosecond timestampsFieldDataType::ProtocolType- Protocol numbersFieldDataType::Vec- Raw byte arraysFieldDataType::ApplicationId- Application identifiers
How It Works
- Without registration: Unknown enterprise fields are parsed as raw bytes (
FieldValue::Vec) - With registration: Registered enterprise fields are automatically parsed according to their specified data type
- Field names: The
nameparameter is used for debugging and can help identify fields in logs
Example
See examples/custom_enterprise_fields.rs for a complete working example.
V9/IPFIX Notes
Parse the data (&[u8]) like any other version. The parser (NetflowParser) caches parsed templates using LRU eviction, so you can send header/data flowset combos and it will use the cached templates. Templates are automatically cached and evicted when the cache limit is reached.
Template Cache Access: Use the introspection methods to inspect template cache state without affecting LRU ordering:
use NetflowParser;
let parser = default;
// Check if a template exists (doesn't affect LRU)
if parser.has_v9_template
// Get cache stats
let stats = parser.v9_cache_stats;
println!;
// List all template IDs
let template_ids = parser.v9_template_ids;
println!;
IPFIX Note: We only parse sequence number and domain id, it is up to you if you wish to validate it.
To access templates flowset of a processed V9/IPFix flowset you can find the flowsets attribute on the Parsed Record. In there you can find Templates, Option Templates, and Data Flowsets.
Performance & Thread Safety
Thread Safety
Parsers (NetflowParser, V9Parser, IPFixParser) are not thread-safe and should not be shared across threads without external synchronization. Each parser maintains internal state (template caches) that is modified during parsing.
Recommended pattern for multi-threaded applications:
- Create one parser instance per thread
- Each thread processes packets from a single router/source
- See
examples/netflow_udp_listener_multi_threaded.rsfor implementation example
Performance Optimizations
This library includes several performance optimizations:
- Single-pass field caching - NetflowCommon conversions use efficient single-pass lookups
- Minimal cloning - Template storage avoids unnecessary vector clones
- Optimized string processing - Single-pass filtering and prefix stripping
- Capacity pre-allocation - Vectors pre-allocate when sizes are known
- Bounded error buffers - Error handling limits memory consumption to prevent exhaustion
Best practices for optimal performance:
- Reuse parser instances instead of creating new ones for each packet
- Use
iter_packets()instead ofparse_bytes()when you don't need all packets in a Vec - Use
parse_bytes_as_netflow_common_flowsets()when you only need flow data - For V9/IPFIX, batch process packets from the same source to maximize template cache hits
Features
parse_unknown_fields- When enabled fields not listed in this library will attempt to be parsed as a Vec of bytes and the field_number listed. When disabled an error is thrown when attempting to parse those fields. Enabled by default.netflow_common- When enabled providesNetflowCommonandNetflowCommonFlowSetstructures for working with common fields across different Netflow versions. Disabled by default.
Included Examples
Examples have been included mainly for those who want to use this parser to read from a Socket and parse netflow. In those cases with V9/IPFix it is best to create a new parser for each router. There are both single threaded and multi-threaded examples in the examples directory.
Examples that listen on a specific port use 9995 by default, however netflow can be configurated to use a variety of URP ports:
- 2055: The most widely recognized default for NetFlow.
- 9995 / 9996: Popular alternatives, especially with Cisco devices.
- 9025, 9026: Other recognized port options.
- 6343: The default for sFlow, often used alongside NetFlow.
- 4739: The default port for IPFIX (a NetFlow successor).
To run:
cargo run --example netflow_udp_listener_multi_threaded
cargo run --example netflow_udp_listener_single_threaded
cargo run --example netflow_udp_listener_tokio
cargo run --example netflow_pcap
cargo run --example manual_ipfix_creation
cargo run --example custom_enterprise_fields
The pcap example also shows how to cache flows that have not yet discovered a template. The custom_enterprise_fields example demonstrates how to register vendor-specific IPFIX fields.
Support My Work
If you find my work helpful, consider supporting me!