/*********************************************************************** * Linux Socketcan Client Server Demo Hacking * Description: * This article is mainly to understand Linux on the basic use of Socketcan, content and Linux on the * network programming almost. * 2016-3-28 Shenzhen Nanshan Ping Shan village Zengjianfeng ********************************************************** ************/one, cat client.c #include<sys/ioctl.h>#include<net/if.h>#include<linux/can.h>#ifndef Pf_can#definePf_can 29#endif#ifndef Af_can#defineAf_can Pf_can#endif intMain () {ints; unsignedLongnbytes; structSockaddr_can addr; structIfreq IFR; structCan_frame frame; //Create a Socketcans =socket (Pf_can,sock_raw,can_raw); //set some parameters, this is the device number of the can network usedstrcpy ((Char*) (Ifr.ifr_name),"Can0"); IOCTL (S,siocgifindex,&IFR); printf ("can0 can_ifindex =%x\n", Ifr.ifr_ifindex); //set up to use the CAN protocoladdr.can_family =Af_can; Addr.can_ifindex=Ifr.ifr_ifindex; Bind (S, (structsockaddr*) &addr,sizeof(addr)); //set the device ID to send toframe.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); //Send DataNbytes = SendTo (S,&frame,sizeof(structCan_frame),0,(structsockaddr*) &addr,sizeof(addr)); return 0; } II, cat server.c #include<sys/ioctl.h>#include<net/if.h>#include<linux/can.h>#ifndef Pf_can#definePf_can 29#endif#ifndef Af_can#defineAf_can Pf_can#endif intMain () {ints; unsignedLongNbytes,len; structSockaddr_can addr; structIfreq IFR; structCan_frame frame; //Create a Socketcans =socket (Pf_can,sock_raw,can_raw); //Specify the can network usedstrcpy (Ifr.ifr_name,"Can0"); IOCTL (S,siocgifindex,&IFR); printf ("can0 can_ifindex =%x\n", Ifr.ifr_ifindex); //specifies the protocol to use, and binds//bind to all enabled can interfaceaddr.can_family =Af_can; Addr.can_ifindex=0; Bind (S, (structsockaddr*) &addr,sizeof(addr)); //Get DataNbytes = Recvfrom (S,&frame,sizeof(structCan_frame),0,(structSOCKADDR *) &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; }
Linux Socketcan Client Server demo hacking