【CAN】在linux中读取监听控制器局域网CAN数据帧操作 (二) 之 C++代码实现

2023-12-15 09:30:25

可以使用 SocketCAN 接口库来实现对 can0 接口的数据帧读取,使用 SocketCAN 接口,将其绑定到 can0 接口,并循环读取接收到的 CAN 数据帧。

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>

int main() {
    // 创建 SocketCAN 套接字
    int soc = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (soc == -1) {
        std::cerr << "Error opening socket." << std::endl;
        return 1;
    }

    // 设置 CAN 接口名称
    struct ifreq ifr;
    std::strcpy(ifr.ifr_name, "can0");
    ioctl(soc, SIOCGIFINDEX, &ifr);

    // 将套接字绑定到 CAN 接口
    struct sockaddr_can addr;
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    if (bind(soc, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1) {
        std::cerr << "Error binding socket to interface." << std::endl;
        close(soc);
        return 1;
    }

    while (true) {
        struct can_frame frame;
        ssize_t nbytes = read(soc, &frame, sizeof(struct can_frame));

        if (nbytes < 0) {
            std::cerr << "Error reading from socket." << std::endl;
            break;
        }

        if (nbytes < sizeof(struct can_frame)) {
            std::cerr << "Incomplete CAN frame received." << std::endl;
            continue;
        }

        // 处理接收到的 CAN 数据帧
        std::cout << "Received CAN frame ID: " << frame.can_id << ", Data: ";
        for (int i = 0; i < frame.can_dlc; ++i) {
            std::cout << std::hex << static_cast<int>(frame.data[i]) << " ";
        }
        std::cout << std::dec << std::endl;
    }

    // 关闭套接字
    close(soc);

    return 0;
}

文章来源:https://blog.csdn.net/qq_54199287/article/details/134996029
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。