Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
SocketCan.cxx
Go to the documentation of this file.
1
35#include "utils/SocketCan.hxx"
36#include "can_frame.h"
37#include <string.h>
38
39#if defined(__linux__)
40
41#include <errno.h>
42#include <linux/sockios.h>
43#include <net/if.h>
44#include <stdio.h>
45#include <sys/ioctl.h>
46
53#define ERRNOLOG(where, x...) \
54 do \
55 { \
56 if ((x) < 0) \
57 { \
58 perror(where); \
59 return -1; \
60 } \
61 } while (0)
62
63int socketcan_open(const char *device, int loopback)
64{
65 int s;
66 struct sockaddr_can addr;
67 struct ifreq ifr;
68
69 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
70 ERRNOLOG("socket", s);
71
72 // Set the blocking limit to the minimum allowed, typically 1024 in Linux
73 int sndbuf = 0;
74 ERRNOLOG("setsockopt(sndbuf)",
75 setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)));
76
77 // turn on/off loopback
78 ERRNOLOG("setsockopt(loopback)",
80 s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback)));
81
82 // setup error notifications
83 can_err_mask_t err_mask = CAN_ERR_TX_TIMEOUT | CAN_ERR_LOSTARB |
84 CAN_ERR_CRTL | CAN_ERR_PROT | CAN_ERR_TRX | CAN_ERR_ACK |
85 CAN_ERR_BUSOFF | CAN_ERR_BUSERROR | CAN_ERR_RESTARTED;
86 ERRNOLOG("setsockopt(filter)",
88 s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &err_mask, sizeof(err_mask)));
89 strcpy(ifr.ifr_name, device);
90
91 ERRNOLOG("interface set", ::ioctl(s, SIOCGIFINDEX, &ifr));
92
93 addr.can_family = AF_CAN;
94 addr.can_ifindex = ifr.ifr_ifindex;
95
96 ERRNOLOG("bind", bind(s, (struct sockaddr *)&addr, sizeof(addr)));
97
98 return s;
99}
100
101#endif
int ioctl(int fd, unsigned long int key,...)
Request and ioctl transaction.
Definition Fileio.cxx:452
int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len)
Set the socket options.
Definition Socket.cxx:255
int bind(int socket, const struct sockaddr *address, socklen_t address_len)
Bind a name to a socket.
Definition Socket.cxx:159
int socket(int domain, int type, int protocol)
Create an unbound socket in a communications domain.
Definition Socket.cxx:144
#define SOCK_RAW
Raw Socket.
Definition socket.h:51
#define SOL_SOCKET
socket option category
Definition socket.h:64
IPv4 socket address.
Definition socket.h:83