1 /**************************************************************/
2 /* CAN system calls example */
3 /* Author: Michal Sojka, Czech Technical University in Prague */
4 /* License: Public domain */
5 /**************************************************************/
15 #include <sys/socket.h>
16 #include <linux/if_packet.h>
17 #include <net/ethernet.h> /* the L2 protocols */
18 #include <sys/ioctl.h>
19 #include <arpa/inet.h>
23 #define FRAME_SIZE 128
24 #define BLOCK_SIZE 4096
26 #define FRAME_NR (BLOCK_NR*(BLOCK_SIZE/FRAME_SIZE))
31 int init_mmap_socket(const char *dev)
34 struct sockaddr_ll addr;
37 sock = CHECK(socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)));
40 CHECK(setsockopt(sock, SOL_PACKET, PACKET_VERSION, &val, sizeof(val)));
42 strncpy (ifr.ifr_name, dev, sizeof(ifr.ifr_name));
43 CHECK(ioctl(sock, SIOCGIFINDEX, &ifr));
45 addr.sll_family = AF_PACKET;
46 addr.sll_protocol = htons(ETH_P_ALL);
47 addr.sll_ifindex = ifr.ifr_ifindex;
49 CHECK(bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_ll)));
51 struct tpacket_req req = {
52 .tp_block_size = BLOCK_SIZE,
53 .tp_frame_size = FRAME_SIZE,
54 .tp_block_nr = BLOCK_NR,
55 .tp_frame_nr = FRAME_NR,
57 CHECK(setsockopt(sock, SOL_PACKET, PACKET_RX_RING, (char *)&req, sizeof(req)));
59 rx_ring_buffer = (char*)CHECKPTR(mmap(0, BLOCK_SIZE*BLOCK_NR, PROT_READ|PROT_WRITE, MAP_SHARED, sock, 0));
65 void can_rx_mmap(int sock)
67 volatile struct tpacket2_hdr *hdr = rx_ring_buffer + current_frame*FRAME_SIZE;
69 /* Wait for a message to arrive. If the task wake-up overhead
70 * is too high, poll() can be commented out and the
71 * application will busy-wait here. */
72 while (hdr->tp_status == TP_STATUS_KERNEL) {
73 struct pollfd pfd = {.fd = sock, .revents = 0,
74 .events = POLLIN|POLLRDNORM|POLLERR };
75 CHECK(poll(&pfd, 1, -1));
78 struct can_frame *cf = (void*)hdr + hdr->tp_mac;
80 hdr->tp_status = 0; /* Mark the frame as processed */
82 current_frame = (current_frame + 1) % FRAME_NR;
85 int main(int argc, char *argv[])
90 dev = candump_parse_args(argc, argv);
92 sock = init_mmap_socket(dev);