/*********************************************************************** * Linux SocketCan client server demo hacking * 说明: * 本文主要是解读Linux上的SocketCan的基本使用方法,内容和Linux上的 * 网络编程差不多。 * * 2016-3-28 深圳 南山平山村 曾剑锋 **********************************************************************/ 一、cat client.c #include <sys/ioctl.h> #include <net/if.h> #include <linux/can.h> #ifndef PF_CAN #define PF_CAN 29 #endif #ifndef AF_CAN #define AF_CAN PF_CAN #endif int main() { int s; unsigned long nbytes; struct sockaddr_can addr; struct ifreq ifr; struct can_frame frame; // 创建一个SocketCan s = socket(PF_CAN,SOCK_RAW,CAN_RAW); // 设置一些参数,这个是使用的can网络的设备号 strcpy((char *)(ifr.ifr_name),"can0"); ioctl(s,SIOCGIFINDEX,&ifr); printf("can0 can_ifindex = %x\n",ifr.ifr_ifindex); // 设置使用CAN协议 addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; bind(s,(struct sockaddr*)&addr,sizeof(addr)); // 设置发送到的设备id frame.can_id = 0x123; strcpy((char *)frame.data,"hello"); frame.can_dlc = strlen(frame.data); printf("Send a CAN frame from interface %s\n",ifr.ifr_name); // 发送数据 nbytes = sendto(s,&frame,sizeof(struct can_frame),0,(struct sockaddr*)&addr,sizeof(addr)); return 0; } 二、cat server.c #include <sys/ioctl.h> #include <net/if.h> #include <linux/can.h> #ifndef PF_CAN #define PF_CAN 29 #endif #ifndef AF_CAN #define AF_CAN PF_CAN #endif int main() { int s; unsigned long nbytes,len; struct sockaddr_can addr; struct ifreq ifr; struct can_frame frame; // 创建一个SocketCan s = socket(PF_CAN,SOCK_RAW,CAN_RAW); // 指定使用的Can网络 strcpy(ifr.ifr_name,"can0"); ioctl(s,SIOCGIFINDEX,&ifr); printf("can0 can_ifindex = %x\n",ifr.ifr_ifindex); // 指定使用的协议,并绑定 //bind to all enabled can interface addr.can_family = AF_CAN; addr.can_ifindex =0; bind(s,(struct sockaddr*)&addr,sizeof(addr)); // 获取数据 nbytes = recvfrom(s,&frame,sizeof(struct can_frame),0,(struct sockaddr *)&addr,&len); /*get interface name of the received CAN frame*/ ifr.ifr_ifindex = addr.can_ifindex; ioctl(s,SIOCGIFNAME,&ifr); printf("Received a CAN frame from interface %s\n",ifr.ifr_name); printf("frame message\n" "--can_id = %x\n" "--can_dlc = %x\n" "--data = %s\n",frame.can_id,frame.can_dlc,frame.data); return 0; }