-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasio_ethernet.hpp
More file actions
executable file
·96 lines (78 loc) · 2.64 KB
/
asio_ethernet.hpp
File metadata and controls
executable file
·96 lines (78 loc) · 2.64 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
88
89
90
91
92
93
94
95
96
#pragma once
#ifdef ASIO_STANDALONE
#include <asio.hpp>
namespace io = asio;
#else
#include <boost/asio.hpp>
namespace io = boost::asio;
#endif
#include <net/if_arp.h>
#include <iostream>
namespace asio {
namespace phy {
class ethernet {
public:
typedef io::detail::array<unsigned char, 6> bytes_type;
public:
ethernet(io::ip::tcp::endpoint epoint, const std::string& devname = "eth0")
: endpoint(epoint),
devicename(devname),
valid(false) {
if (endpoint.address().is_v4()) {
valid = macaddr_ipv4();
}
else {
std::cerr << "IPv6 is not supported." << std::endl;
valid = false;
}
}
bytes_type macaddr() const {
return mac;
}
std::string to_string() const {
std::string str(20, '\0');
if (isValid()) {
sprintf(&str[0], "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
return str;
}
bool isValid() const {
return valid;
}
private:
bool macaddr_ipv4() {
struct auto_close {
auto_close() : fd(-1) { }
~auto_close() { if (fd != -1) close(fd); }
int fd;
} handle;
struct arpreq areq;
struct sockaddr_in *sin;
struct in_addr addr;
memcpy(&addr.s_addr, endpoint.address().to_v4().to_bytes().data(), 4);
memset(&areq, 0, sizeof(areq));
sin = (struct sockaddr_in *) &areq.arp_pa;
sin->sin_family = AF_INET;
sin->sin_addr = addr;
sin = (struct sockaddr_in *) &areq.arp_ha;
sin->sin_family = ARPHRD_ETHER;
std::copy_n(devicename.cbegin(), 15, areq.arp_dev);
if ((handle.fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
return false;
}
if (ioctl(handle.fd, SIOCGARP, (caddr_t) &areq) == -1) {
perror("-- Error: unable to make ARP request, error");
return false;
}
std::copy_n(areq.arp_ha.sa_data, mac.size(), mac.begin());
return true;
}
private:
io::ip::tcp::endpoint endpoint;
bytes_type mac;
bool valid;
std::string devicename;
};
} // namespace phy
} // namespace asio