Blame view

src/linux/can_address.cpp 1.24 KB
ea9eaf95   Peter M. Groen   Fixed Headers
1
2
  #include "socket-cpp/can_address.h"
  #include "socket-cpp/socket.h"
48b4c725   Peter M. Groen   Setting up Socket-pp
3
4
5
6
7
8
  #include <cstring>
  #include <stdexcept>
  #include <sys/ioctl.h>
  #include <net/if.h>
  
  using namespace std;
ea9eaf95   Peter M. Groen   Fixed Headers
9
  using namespace osdev::components::socket-cpp;
48b4c725   Peter M. Groen   Setting up Socket-pp
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
  
  constexpr sa_family_t can_address::ADDRESS_FAMILY;
  
  // --------------------------------------------------------------------------
  
  can_address::can_address(unsigned ifindex) : addr_{}
  {
  	addr_.can_family = AF_CAN;
  	addr_.can_ifindex = ifindex;
  }
  
  can_address::can_address(const string& iface) : addr_{}
  {
  	unsigned idx = if_nametoindex(iface.c_str());
  
  	if (idx != 0) {
  		addr_.can_family = AF_CAN;
  		addr_.can_ifindex = idx;
  	}
  }
  
  can_address::can_address(const sockaddr& addr)
  {
      auto domain = addr.sa_family;
      if (domain != AF_CAN)
          throw std::invalid_argument("Not a SocketCAN address");
  
      std::memcpy(&addr_, &addr, sizeof(sockaddr));
  }
  
  string can_address::iface() const
  {
  	if (addr_.can_family == AF_UNSPEC)
  		return string("none");
  
  	if (addr_.can_ifindex == 0)
  		return string("any");
  
  	char buf[IF_NAMESIZE];
  	const char* iface = if_indextoname(addr_.can_ifindex, buf);
  
  	return string(iface ? iface : "unknown");
  }
  
48b4c725   Peter M. Groen   Setting up Socket-pp
54
55
56
57
58
  ostream& operator<<(ostream& os, const can_address& addr)
  {
  	os << "can:" << addr.iface();
  	return os;
  }