Minimal toolkit to analyze CAN traffic and shape (rate-limit/drop/remap) frames.
Targets Linux SocketCAN (e.g., can0, vcan0). Windows is supported via WSL2 or vendor backends through python-can.
- SocketCAN Traffic Shaper & Analyzer
- 1) What is SocketCAN?
- 2) Project Goals
- 3) Quick Start
- 4) Traffic Shaping: Approaches (Implemented)
- 5) Project Structure (Current Implementation)
- 6) Usage (Implemented Modules)
- 7) Development (Current State)
- 8) Testing & Benchmarking (Implemented)
- 9) Implementation Status & Future Work
- 10) FAQs
- 11) References
SocketCAN is the set of openβsource CAN (Controller Area Network) drivers and a Linuxβkernel networking stack that exposes CAN devices via the familiar Berkeley sockets API (PF_CAN). In practice, it lets you:
- Use
ip,ifconfig,tc, and other standard net tools with CAN interfaces. - Work with real CAN adapters (e.g., USBβtoβCAN) and virtual interfaces (e.g.,
vcan) for simulation. - Send/receive classic CAN (11/29βbit IDs) and, on supported hardware, CAN FD.
Key ideas: a CAN interface shows up as a Linux net device (e.g.,
can0,vcan0), and frames are read/written using sockets instead of vendor SDKs.
A practical toolkit to shape (prioritize, pace, rateβlimit) and analyze CAN traffic using SocketCAN β with a friendly CLI, repeatable scenarios, and clear metrics.
Core pillars:
- Traffic shaping: prioritize IDs, throttle rates, burst/latency control, and queue tuning.
- Analysis: live sniffing, stats, histograms (interβarrival, latency), ID filters/whitelists/blacklists.
- Emulation: reproducible testbeds using
vcanso contributors donβt need hardware. - Extensibility: clean modules for new shaping policies and analyzers.
- Linux (Ubuntu/Debian recommended) or
- WSL2 on Windows.
If youβre on Windows, we recommend WSL2 + Ubuntu.
Official docs:
- Install WSL: https://learn.microsoft.com/windows/wsl/install
Quick checks:
wsl -l -v # list installed distros and versions
wsl --set-version <Distro> 2
wsl --install # one-shot install on supported Windows versionsTip: Keep WSL (Store package) and the WSL kernel updated before troubleshooting modules.
Most recent WSL2 kernels ship vcan and can as modules. Verify and enable:
# Inside your WSL2 Ubuntu shell
uname -r # Note kernel version
sudo modprobe vcan # Load virtual CAN module (no output on success)
sudo modprobe can # Base CAN stack module; usually auto-loaded
lsmod | grep -E "^(vcan|can)" || echo "Modules not loaded"If modprobe vcan fails with βmodule not foundβ, you have two options:
- Use an official custom-kernel route
- WSL advanced settings & custom kernel path (
.wslconfig): https://learn.microsoft.com/windows/wsl/wsl-config - Microsoft WSL2 kernel repo (source & configs): https://github.com/microsoft/WSL2-Linux-Kernel
- Community how-to for Microsoft kernel v6 (semi-official Learn community page): https://learn.microsoft.com/en-us/community/content/wsl-user-msft-kernel-v6
- WSL advanced settings & custom kernel path (
- Community guide (example below)
- Enabling SocketCAN on WSL2: https://gist.github.com/manavortex/cdaf9540784808e5848cbec744d49a19
# Load the virtual CAN kernel module
sudo modprobe vcan
# Create vcan0 and bring it up
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0
# Verify
ip -details -statistics link show vcan0sudo apt update
sudo apt install -y iproute2 can-utilsIn terminal A:
candump vcan0In terminal B (send a sample frame):
cansend vcan0 123#DEADBEEF
# or generate traffic
cangen vcan0 -g 5 # 5 ms gap between framesYou should see frames in terminal A.
Use usbipd-win on Windows to attach a USB device to WSL2, then bring the interface up inside WSL:
# On Windows PowerShell (Admin): list and attach by busid
usbipd wsl list
usbipd wsl attach --busid <BUSID>Back in WSL:
# Example: bring up classic CAN at 500 kbit/s
sudo ip link set can0 up type can bitrate 500000
# optional: tune TX queue length
sudo ip link set can0 txqueuelen 100
# teardown
sudo ip link set can0 downResources:
- Microsoft usbipd guide: https://learn.microsoft.com/windows/wsl/connect-usb
usbipd-winwiki (WSL support): https://github.com/dorssel/usbipd-win/wiki/WSL-support
If you rely on Docker Desktop in WSL, be cautious with custom kernels; some tools donβt support nonβdefault kernels. Weβll track compatibility notes in
docs/wsl-kernel.md.
Traffic shaping in CAN can be approached at several levels. Current implementation focuses on:
-
Userβspace bridge foundation (implemented)
- Pass-through CAN bridge with real-time statistics and proper resource cleanup.
- Foundation for future token bucket rate limiting implementation.
- Pros: portable, predictable, comprehensive test coverage.
- Status: Bridge ready, token bucket components for future integration.
-
Queue tuning
- Adjust driver/netdev queue sizes (
txqueuelen), apply prioritization in userβspace queues before send.
- Adjust driver/netdev queue sizes (
-
Kernel qdisc experiments (later)
- Where feasible, explore
tcβbased queuing/priority on CAN netdevs and document what is (and isnβt) supported for CAN.
- Where feasible, explore
-
IDβbased prioritization
- Map arbitration IDs (or ranges/masks) to priority classes and schedule accordingly (e.g., safetyβcritical vs diagnostic).
Current Status: Pass-through bridge implemented with comprehensive testing. Ready for token bucket integration or further development.
.
βββ README.md # You are here
βββ docs/
β βββ roadmap.md # Development roadmap and status
β βββ testing.md # Testing infrastructure notes
βββ tools/ # Renamed from scripts/
β βββ setup_vcan.sh # Create/teardown vcan interfaces
β βββ shutdown_vcan.sh # Cleanup vcan interfaces
β βββ wsl-env.sh # WSL environment setup helper
βββ src/
β βββ socketcan_sa/ # Main package
β βββ analyzer.py # CAN traffic analysis with CSV export
β βββ shaper.py # Pass-through CAN bridge (traffic shaping foundation)
β βββ rules.py # YAML configuration parser
βββ tests/ # Comprehensive test suites
β βββ test_analyzer*.py # 42 analyzer tests (5 categories)
β βββ test_shaper*.py # 35 shaper tests (100% coverage)
β βββ test_rules*.py # 65 rules tests (98.72% coverage)
β βββ conftest.py # Test fixtures and utilities
β βββ sample_frames.py # Test data generation
βββ configs/
β βββ rules.dev.yaml # Example YAML configuration
βββ pyproject.toml # Python packaging configuration
The core modules can be imported and used directly:
# Analyze CAN traffic with CSV export
from socketcan_sa.analyzer import analyze
analyze("vcan0", interval=2.0, csv_path="traffic.csv")
# Pass-through bridge (foundation for traffic shaping)
from socketcan_sa.shaper import run_bridge
import threading
stop_event = threading.Event()
run_bridge("vcan0", "vcan1", stats_interval=1.0)
# Parse YAML rules configuration
from socketcan_sa.rules import load_rules
rules = load_rules("configs/rules.dev.yaml")
limits = rules["limits"] # Per-ID rate limits
drops = rules["drop"] # IDs to drop
remaps = rules["remap"] # ID remappingIntegration Status: Core components ready. CLI integration available for future development.
- Language: Python 3.12+ with type hints and comprehensive testing
- Dependencies:
python-can,PyYAML,richfor CLI output,hypothesisfor property testing - Testing:
pytestwith coverage reporting, 5-category test methodology - Quality: Type hints, docstrings, 95%+ test coverage across all modules
# WSL2 environment (recommended)
python3 -m venv .venv-wsl
source .venv-wsl/bin/activate
pip install -e .
# Run comprehensive test suite
python -m pytest tests/ -v
# Check coverage
python -m pytest tests/ --cov=socketcan_sa --cov-report=html- 5-Category Test Methodology: Coverage, Integration, Performance, Properties (hypothesis), Stress
- Test Coverage: 142 total tests across all modules with 95%+ coverage
- Performance Benchmarks: Bridge throughput (1000+ fps), rules parsing scalability, analyzer throughput
- Property-Based Testing: Mathematical invariants validation with Hypothesis framework
- Integration Tests: Real vcan interface testing with automotive and industrial scenarios
- Core Components: Analyzer, Pass-through bridge, YAML rules parser
- Comprehensive Testing: 142 tests with property-based validation
- YAML Configuration: Full CAN ID parsing with automotive/industrial examples
- Performance Analysis: Benchmarking and memory efficiency testing
- Integration Layer: Bridge components for complete traffic shaping pipeline
- CLI Interface: Command-line tools for ease of use
- Hardware Integration: Real CAN adapter support beyond vcan testing
Q: Do I need hardware?
A: No. Start with vcan. Hardware integration docs will come later.
Q: Is Windows supported?
A: Use WSL2 with vcan for dev. Native Windows CAN is outβofβscope initially.
Q: CAN FD?
A: Planned where hardware/kernel support exists; weβll gate it behind a flag.
-
WSL install (official): https://learn.microsoft.com/windows/wsl/install
-
WSL manual install (official): https://learn.microsoft.com/windows/wsl/install-manual
-
WSL basic commands (official): https://learn.microsoft.com/windows/wsl/basic-commands
-
WSL advanced settings & custom kernel path (official): https://learn.microsoft.com/windows/wsl/wsl-config
-
WSL kernel release notes (official): https://learn.microsoft.com/windows/wsl/kernel-release-notes
-
USB passthrough to WSL (official): https://learn.microsoft.com/windows/wsl/connect-usb
-
usbipd-winwiki (WSL usage): https://github.com/dorssel/usbipd-win/wiki/WSL-support -
Microsoft WSL2 Kernel repo (source): https://github.com/microsoft/WSL2-Linux-Kernel
-
Community kernel build guide (MS Learn community): https://learn.microsoft.com/en-us/community/content/wsl-user-msft-kernel-v6
-
Community guide (user-supplied): https://gist.github.com/manavortex/cdaf9540784808e5848cbec744d49a19
-
SocketCAN / linux-can docs (to add)
-
can-utils repo (to add)
-
python-can (to add)