-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathWindowsMacAddr.cpp
More file actions
54 lines (44 loc) · 1.85 KB
/
Copy pathWindowsMacAddr.cpp
File metadata and controls
54 lines (44 loc) · 1.85 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
#if defined(ARCH_PORTDUINO) && defined(_WIN32)
// Host-MAC lookup for getMacAddr(), replacing BlueZ on Linux and en0 on macOS.
// Isolated TU: <iphlpapi.h> needs the header trims the env sets, and undoes them here.
#undef WIN32_LEAN_AND_MEAN
#undef NOUSER
#undef NOGDI
// Order is load-bearing, hence the blank lines: winsock2.h must precede
// windows.h, which would otherwise pull in the colliding winsock v1 header.
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
#include <cstring>
#include <memory>
#include <stdint.h>
// Fill dmac with the first up, non-loopback adapter's physical address, else
// return false. Adapter order is stable across reboots, so the identity persists.
bool portduinoWindowsPrimaryMac(uint8_t *dmac)
{
const ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
ULONG bufLen = 15000; // starting size recommended by the API docs
std::unique_ptr<char[]> buf(new char[bufLen]);
auto *addrs = reinterpret_cast<IP_ADAPTER_ADDRESSES *>(buf.get());
ULONG ret = GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, addrs, &bufLen);
if (ret == ERROR_BUFFER_OVERFLOW) {
// bufLen now holds the required size; retry once.
buf.reset(new char[bufLen]);
addrs = reinterpret_cast<IP_ADAPTER_ADDRESSES *>(buf.get());
ret = GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, addrs, &bufLen);
}
if (ret != NO_ERROR)
return false;
for (auto *a = addrs; a != nullptr; a = a->Next) {
if (a->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
continue;
if (a->OperStatus != IfOperStatusUp)
continue;
if (a->PhysicalAddressLength != 6)
continue;
std::memcpy(dmac, a->PhysicalAddress, 6);
return true;
}
return false;
}
#endif // ARCH_PORTDUINO && _WIN32