The Linux C/C++ API allows you to control a SocketCAN interface via a C/C++ application.
If you are looking for help interfacing with SocketCAN from the Linux command-line, see the How To Use SocketCAN With The Command-Line In Linux page.
If you are looking for more information about the CAN bus protocol itself, see the CAN Protocol page.
SocketCAN supports standard frame format (SFF), extended frame format (EFF) and CAN FD frames.
Reading And Writing
The data for reading and writing to the CAN bus is communicated through the
can_frame struct which is declared and defined in
can_id value has the following structure:
[0-28]: CAN identifier (11/29bit)
: Error frame flag (0 = data frame, 1 = error frame)
: Remote transmission request flag (1 = rtr frame)
: Frame format flag (0 = standard 11bit, 1 = extended 29bit)
The padding in the above struct allows data to be aligned to a 64-bit boundary. This allows the user to define their own structs and unions to easily access the data (by casting). For example, you could access all 8-bytes of data as a single 64-bit value if desired.
Note that the
can_id structure does not map directly to the bits present in the arbitration field of a CAN message.
There is also an extended frame struct, called
canfd_frame struct does not have a
can_dlc member to indicate the number of bytes, but rather a len member.
read() system call transfers a
canfd_frame struct from the kernel CAN buffer to the user space.
Data is buffered internally, which means for virtual interfaces, you can do a write, pause, and then read the value back at a later time (you do not have to use separate threads/processes).
libsocketcan is a Linux library that provides some userspace functionality to control a SocketCAN interface. It provides functions such as
Although libsocketcan seems to work fine for physical CAN interfaces (e.g.
can0), I have had issues when using it with a virtual CAN interface (e.g.
vcan0). Specifically, functions such as
can_get_state() do not seem to work correctly.
You can install
libsocketcan on your Linux machine by following the below steps:
~$ git clone https://git.pengutronix.de/git/tools/libsocketcan
Build/install (libsocketcan uses the autotools build system):
1 2 3 4
~$ cd libsocketcan ~/libsocketcan$ ./autogen.sh ~/libsocketcan$ ./configure ~/libsocketcan$ make
You should now have
libsocketcan.a installed to
/usr/local/lib and the header file
libsocketcan.h installed to
https://www.kernel.org/doc/Documentation/networking/can.txt is a great page detailing with the Linux C API for SocketCAN, including code examples and use cases.
The can-utils package source code can be found at https://github.com/linux-can/can-utils. This has great C code examples on how to read and write messages to the SocketCAN interface.
This work is licensed under a Creative Commons Attribution 4.0 International License .
- How To Use SocketCAN With The Command-Line In Linux
- July 2017 Updates
- Consistent Overhead Byte Stuffing (COBS)