Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Bak-Jin-Hyeong/7f65aaea4cf6e7d503c60c25f0865c9e to your computer and use it in GitHub Desktop.
Save Bak-Jin-Hyeong/7f65aaea4cf6e7d503c60c25f0865c9e to your computer and use it in GitHub Desktop.
Find first mac address (windows)
#include "get_first_mac_address_windows.h"
#include <vector>
#include <WinSock2.h>
#include <ws2ipdef.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
std::optional<std::array<uint8_t, 6>> get_first_mac_address()
{
const ULONG flags =
GAA_FLAG_INCLUDE_GATEWAYS |
GAA_FLAG_SKIP_DNS_SERVER |
GAA_FLAG_SKIP_MULTICAST;
char stack_buffer[8192];
std::vector<char> heap_buffer;
auto adapter_0 = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(stack_buffer);
ULONG buffer_length = sizeof(stack_buffer);
const auto error_0 = ::GetAdaptersAddresses(
AF_UNSPEC, flags, nullptr, adapter_0, &buffer_length);
if (error_0 == ERROR_BUFFER_OVERFLOW && buffer_length > 0)
{
heap_buffer.resize(buffer_length);
adapter_0 = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&heap_buffer[0]);
const auto error_1 = ::GetAdaptersAddresses(
AF_UNSPEC, flags, nullptr, adapter_0, &buffer_length);
if (error_1 != NO_ERROR)
{
return std::nullopt;
}
}
else if (error_0 != NO_ERROR)
{
return std::nullopt;
}
BYTE* mac = nullptr;
bool gateway = false;
for (auto adapter = adapter_0; adapter; adapter = adapter->Next)
{
if (adapter->PhysicalAddressLength == 6)
{
if (!mac)
{
// First Mac address
mac = adapter->PhysicalAddress;
}
if (!gateway && adapter->FirstGatewayAddress)
{
// The adapter with the gateway address takes precedence.
mac = adapter->PhysicalAddress;
gateway = true;
}
}
}
if (mac)
{
return std::array<uint8_t, 6>{ mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] };
}
return std::nullopt;
}
#ifndef GET_FIRST_MAC_ADDRESS_WINDOWS__H__
#define GET_FIRST_MAC_ADDRESS_WINDOWS__H__
#include <array>
#include <optional>
#include <utility>
std::optional<std::array<uint8_t, 6>> get_first_mac_address();
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment