Newer
Older
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <linux/can/raw.h>
    int fd;
    struct sockaddr_can addr;
    struct ifreq ifr;
    struct can_frame frame;
    fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (fd < 0) {
        perror("error socket");
    strcpy(ifr.ifr_name, "can0");
    ioctl(fd, SIOCGIFINDEX, &ifr);
    memset(&addr, 0, sizeof(addr));
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror("error bind");
        exit(EXIT_FAILURE);
    }
    frame.can_id = 0x708;
    frame.can_dlc = 2;
    frame.data[0] = 0xff;
    frame.data[1] = 0xff; // 0b0100 0000
    if (write(fd, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
        perror("error write");
        exit(EXIT_FAILURE);
    // int nbytes;
    // struct can_frame readframe;
    // nbytes = read(fd, &readframe, sizeof(struct can_frame));
    // if (nbytes < 0) {
    //     perror("reading");
    //     exit(EXIT_FAILURE);
    // }
    // printf("0x%x [%d]\n", readframe.can_id, readframe.can_dlc);
    // for (int i = 0; i < frame.can_dlc; i++)
    // {
    //     printf("0x\n", readframe.data[i]);
    // }