Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start / stop CAN boards from userspace using libsocketcan

I am trying to start / stop CAN boards or to update their baudrate using SocketCAN from userspace. My tests are performed on PeakSystem and IXXAT USB-to-CAN V1/V2 boards.

My first attempt was to use visudo and to enable NOPASSWD to "ip link set ...", and then to call "sudo ip link set ..." in my C++ code. Complete visudo line is:

%sudo  ALL=(ALL:ALL) NOPASSWD: /bin/ip link set can[0123456789]* type can bitrate [0123456789]*, /bin/ip link set can[0123456789]* up, /bin/ip link set can[0123456789]* down

Then, I tried with Linux capabilities by adding capabilities to /bin/ip. That allows me to call "ip link set ..." from my C++ code which was even better. Add capabilities command:

sudo setcap cap_net_raw,cap_net_admin+ep /bin/ip

But then I discovered libsocketcan which is a far better approach than calling command lines from C++. However when calling "can_set_bitrate" or "can_do_start", I have an error "RTNETLINK: Operation not permitted". But things are working fine when my program is launched as root. Other functions like can_get_state are working fine in userspace (actually, they are returning : 4 -> CAN_STATE_STOPPED). I tried to adding capabilities to my program without any success ""sudo setcap cap_net_raw,cap_net_admin+ep ./myprogram".

How can I allow my program to use libsocketcan in userspace?

Thanks for your help!

like image 756
Fylhan Avatar asked Jun 11 '26 18:06

Fylhan


1 Answers

sudo setcap cap_net_raw,cap_net_admin+ep your_executable is the solution. You may need to compile with -Wl,-rpath so your program finds its shared libraries (also see this answer)

like image 73
Laurenz Avatar answered Jun 14 '26 09:06

Laurenz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!