-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCANSocket.cpp
More file actions
87 lines (65 loc) · 2.1 KB
/
Copy pathCANSocket.cpp
File metadata and controls
87 lines (65 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "CANSocket.h"
#include <linux/can.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <cstring>
using namespace NET;
CANSocket::CANSocket( int type, int protocol)
: SimpleSocket( CAN, type, protocol)
{}
void CANSocket::connect( std::string_view interface)
{
sockaddr_can addr;
addr.can_family = AF_CAN;
addr.can_ifindex = getInterfaceIndex(interface);
if( ::connect( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
throw SocketException("Connect failed (connect)");
}
void CANSocket::bind( std::string_view interface)
{
sockaddr_can addr;
addr.can_family = AF_CAN;
addr.can_ifindex = getInterfaceIndex(interface);
if( ::bind( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
throw SocketException("Set of interface failed (bind)");
}
std::string CANSocket::getLocalInterface() const
{
sockaddr_can addr;
socklen_t addr_len = sizeof(addr);
if( getsockname( m_socket, (sockaddr*) &addr, &addr_len) < 0)
throw SocketException("Fetch of interface failed (getsockname)");
return getInterfaceName(addr);
}
std::string CANSocket::getForeignInterface() const
{
sockaddr_can addr;
socklen_t addr_len = sizeof(addr);
if( getpeername( m_socket, (sockaddr*) &addr, &addr_len) < 0)
throw SocketException("Fetch of interface failed (getsockname)");
return getInterfaceName(addr);
}
std::string CANSocket::getInterfaceName( const sockaddr_can& addr) const
{
struct ifreq ifr;
ifr.ifr_ifindex = addr.can_ifindex;
if( ioctl( m_socket, SIOCGIFNAME, &ifr) < 0)
throw SocketException("ioctl failed (getInterfaceName)");
return std::string(ifr.ifr_name);
}
int CANSocket::getInterfaceIndex( std::string_view interface) const
{
const int len = interface.length();
// binds to all interfaces
if( len == 0) return 0;
// needed space is size plus null character
if( len >= IF_NAMESIZE-1)
throw SocketException("Interface name is too long", false);
struct ifreq ifr;
std::memcpy( ifr.ifr_name, interface.data(), len);
ifr.ifr_name[len] = 0;
if( ioctl( m_socket, SIOCGIFINDEX, &ifr) < 0)
throw SocketException("ioctl failed (getInterfaceIndex)");
return ifr.ifr_ifindex;
}