]> rtime.felk.cvut.cz Git - sojka/can-syscalls-examples.git/blobdiff - cansend-sendmmsg.c
Add cansend examples
[sojka/can-syscalls-examples.git] / cansend-sendmmsg.c
diff --git a/cansend-sendmmsg.c b/cansend-sendmmsg.c
new file mode 100644 (file)
index 0000000..c14f4cc
--- /dev/null
@@ -0,0 +1,74 @@
+/**************************************************************/
+/* CAN system calls example                                  */
+/* Author: Michal Sojka, Czech Technical University in Prague */
+/* License: Public domain                                    */
+/**************************************************************/
+
+#define _GNU_SOURCE
+
+#include "common.h"
+
+#include <linux/can.h>
+#include <net/if.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+
+#define MMSG_MAX 64
+
+struct mmsghdr msgs[MMSG_MAX];
+struct iovec iovecs[MMSG_MAX];
+struct can_frame cf[MMSG_MAX];
+
+int init_sendmmsg(const char *dev)
+{
+       int sock, i;
+       struct sockaddr_can addr;
+       struct ifreq ifr;
+
+       sock = CHECK(socket(PF_CAN, SOCK_RAW, CAN_RAW));
+
+       strncpy(ifr.ifr_name, dev, sizeof(ifr.ifr_name));
+       if (-1 == ioctl(sock, SIOCGIFINDEX, &ifr)) {
+               perror(dev);
+               exit(1);
+       }
+
+       addr.can_family = AF_CAN;
+       addr.can_ifindex = ifr.ifr_ifindex;
+
+       CHECK(bind(sock, (struct sockaddr *)&addr, sizeof(addr)));
+
+       memset(msgs, 0, sizeof(msgs));
+       memset(iovecs, 0, sizeof(iovecs));
+       for (i = 0; i < MMSG_MAX; i++) {
+               iovecs[i].iov_base         = &cf[i];
+               iovecs[i].iov_len          = sizeof(cf[i]);
+               msgs[i].msg_hdr.msg_iov    = &iovecs[i];
+               msgs[i].msg_hdr.msg_iovlen = 1;
+       }
+
+       return sock;
+}
+
+void can_sendmmsg(int sock, int count)
+{
+       CHECK(sendmmsg(sock, msgs, count, 0));
+}
+
+int main(int argc, char *argv[])
+{
+       const char *dev;
+       int sock, count;
+
+       dev = cansend_parse_args(argc, argv, &count, cf, MMSG_MAX);
+
+       sock = init_sendmmsg(dev);
+
+       can_sendmmsg(sock, count);
+
+       return 0;
+}