Vehicle Communication and Networking · Linux networking
SocketCAN
Also known as Linux-CAN, PF_CAN, can0, vcan, can-utils
The Linux kernel's CAN subsystem, which implements CAN protocols on the Berkeley socket API and the Linux network stack and exposes CAN controllers as network interfaces such as can0.
Explanation
Earlier Linux CAN drivers were character devices with vendor-specific interfaces. SocketCAN instead implements CAN device drivers as network interfaces and provides the PF_CAN protocol family, so applications use familiar socket calls and several programs can use the same bus at once. Raw sockets send and receive individual frames, broadcast-manager (BCM) sockets handle cyclic transmission and content filtering in the kernel, and further protocols such as ISO-TP and J1939 are available.
Frames are represented by struct can_frame for Classical CAN and struct canfd_frame for CAN FD. The 32-bit can_id field carries the 11-bit or 29-bit identifier plus flags for extended format, remote frames and error frames. Each socket can set receive filters that match identifiers by mask, and virtual CAN interfaces (vcan) allow testing without hardware.
SocketCAN gives no timing guarantees by itself. Latency depends on the driver, interrupt handling, scheduling and socket buffering, so real-time CAN applications need tuning, for example PREEMPT_RT and appropriate thread priorities.
How it works
A program creates a socket with PF_CAN and the CAN_RAW protocol, binds it to an interface such as can0, optionally sets filters, and then reads and writes can_frame structures. Outgoing frames pass through the network stack to the driver's transmit queue. Frames received by the controller are delivered by the driver to every socket whose filters match. The can-utils command-line tools use the same API.
Automotive applications
- Logging and replaying vehicle CAN traffic
- Linux-based gateways and telematics units
- Hardware-in-the-loop test benches
- Diagnostic tools using ISO-TP sockets
Example
A data logger on a Linux ECU opens a raw CAN socket on can1 with a filter for identifiers 0x100 to 0x1FF, timestamps each received frame and writes it to storage. The same code runs unchanged on a developer PC using a virtual vcan0 interface.
An illustrative example: any figures in it are worked numbers, not measurements.
References
- SocketCAN - Controller Area Network (opens in a new tab)
“SocketCAN uses the Berkeley socket API, the Linux network stack and implements the CAN device drivers as network interfaces.”
- ISO 15765-2 (ISO-TP) (opens in a new tab)
Definitions are original summaries. Standards text is not reproduced; follow the links for the official publications.