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

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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;
}

你可能感兴趣的:(学习笔记,c++,单片机,嵌入式硬件,python,linux)