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

可以使用 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SensizliKLoU

感谢您的慷慨支持和鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值