Add SocketCAN support in WSL
If you have followed the steps in Set up build environment for POSIX platform on Ubuntu 22.04 or Windows then you should now have an environment in which you can build and run the POSIX platform executable and this enables experimentation and learning through making your own changes to the codebase.
Linux supports Virtual CAN adapters (vcan), which allow CAN applications to be developed
without CAN hardware. The POSIX build uses a virtual CAN interface.
Recent Microsoft WSL kernels provide the necessary SocketCAN and vcan modules,
so building a custom kernel is not necessary.
The steps below assume you have WSL2 and Ubuntu 22.04 set up
as described in Set up Ubuntu 22.04 in WSL.
In PowerShell or a Windows command prompt, update WSL and check that your Ubuntu distribution uses version 2:
wsl --update
wsl --list --verbose
If the distribution is listed as version 1, see Microsoft’s instructions for changing the WSL version.
If you previously configured a custom kernel, remove its kernel setting from the [wsl2]
section of %UserProfile%\.wslconfig to return to the Microsoft kernel.
Also remove a kernelModules setting if it points to modules for that custom kernel.
Keep any other settings you still need.
See Microsoft’s WSL configuration documentation.
Restart WSL to apply the update and any configuration changes. This stops all running WSL distributions, so save your work first:
wsl --shutdown
Start Ubuntu again and check the running kernel with uname -r.
For example, Microsoft’s
WSL kernel 6.18.35.2 configuration
includes the CAN and vcan modules. If a module below is not found,
check that the update installed a kernel with these modules and that no custom kernel or
custom modules VHD is still configured. Older WSL kernels may not include them.
Each time WSL starts you will need to load the CAN kernel modules…
sudo modprobe can
sudo modprobe can-raw
sudo modprobe vcan
Then create a virtual CAN device as follows. If vcan0 already exists, skip the first command.
sudo ip link add dev vcan0 type vcan
sudo ip link set vcan0 mtu 16
sudo ip link set up vcan0
If this works, ip link show vcan0 should show the interface as UP. For example:
2: vcan0: <NOARP,UP,LOWER_UP> mtu 16 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/can
You can install SocketCAN utilities…
sudo apt install can-utils
and then use the Virtual CAN interface vcan0 with these. eg. In one Ubuntu shell run…
candump vcan0
and at the same time, in another Ubuntu shell run…
cansend vcan0 321#AABBCCDDEEFF
The above command sends a CAN Frame with ID = 0x321 and 6 bytes of data 0xAABBCCDDEEFF to vcan0.
You should see it in the output from candump vcan0 like this…
vcan0 321 [6] AA BB CC DD EE FF
For a description of how to use your POSIX platform build with a Virtual CAN interface, see Working with CAN.