TIL - Virtual CAN interfaces

TIL, Today I Learned, is more of a "I just figured this out: here are my notes, you may find them useful too" rather than a full blog post

There are many scenarios where a virtual Controller Area Network(CAN) interface could be handy. It let you develop and test applications that without an actual physical CAN bus.

My scenario is to play around with Berkley Packet Filter(BPF) [1] and do some data manipulation on recieved CAN frames in kernel space.


We use iproute2 [2] in order to create the virtual CAN interfaces

sudo ip link add dev vcan0 type vcan
sudo ip link add dev vcan1 type vcan

Bring up the interaces

sudo ip link set up vcan0
sudo ip link set up vcan1

You are now able to use can-utils [3] to send and recieve CAN frames.


If you have enabled the CONFIG_CAN_GW in your kernel, then you can create gateway rules and route frames between CAN interfaces cangw (part of can-utils).

Verify that CAN_GW is supported by the kernel

[16:25:10]marcus@goliat:~/git/linux$ zgrep CONFIG_CAN_GW /proc/config.gz

Load kernel module

sudo modprobe can-gw

Create gateway rule to route messages from vcan0 to vcan1 and vice versa

sudo cangw -A -s vcan0 -d vcan1 -e
sudo cangw -A -s vcan1 -d vcan0 -e

The routing is not limited to only virtual CAN interfaces. You can setup gateway rules between real and virtual ones.