Error binding can0 on ApalisiMX8 using socketcan

Hello,

I am using the following code to start socketcan communication in C/C++ for the can0 port on ApalisiMX8 on the Ixora board.
Source: SocketCAN - Controller Area Network — The Linux Kernel documentation

See sample code below.
Issue is that I am always getting a bind error when using can0.
Also tried using /sys/class/net/can0 and /sys/devices/platform/bus@5a000000/5a8d0000.can/net/can0 as alternative names, but still getting a bind error.
What is the correct reference to use?


int s1,s2;
int nbytes;
struct sockaddr_can addr;
struct can_frame frame;
struct ifreq ifr;

//Trying to change name -can0, /sys/devices/platform/bus@5a000000/5a8d0000.can/net/can0, /sys/class/net/can0
const char *ifname = “can0”;

//port1
if((s1 = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
    perror("Error while opening socket \n ");
    return -1;
}
else{
    printf("socket at index %d\n", s1);
}

strcpy(ifr.ifr_name, ifname);
ioctl(s1, SIOCGIFINDEX, &ifr);

addr.can_family  = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;

printf("%s at index %d\n", ifname, ifr.ifr_ifindex);

if(bind(s1, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
    perror("Error in socket bind");
    return -2;
}

Greetings @SJ_BHD,

I have a few questions here about your setup. So you tagged your question Torizon. Is is safe to assume then you’re running this code inside a container on TorizonCore?

If yes, then how are you running this container?

Cause it may be the case you don’t have the CAN interface integrated into this container which may be causing the bind issue you described.

Furthermore what is the exact error you are getting from bind? It may have additional information.

Best Regards,
Jeremias

Hello Jeremias,

I debugged the code and noted that the binding issue for can0 was arising from the following line:

*if(bind(s1, (struct sockaddr )&addr, sizeof(addr)) < 0)

The can0 needs to be recognized as referring to the exact port.

After that I updated the extrapackages option in the Torizon VSCode plugin to contain iproute2.
Also added the following updates in extra params.
cap_add - [“NET_ADMIN”]

This seems to resolve the problem as the term can0 is now recognised as a can socket.

Hi @SJ_BHD,

These are great news! I’m glad you can find the can0 interface now. Can we then mark this post as solved?