C++ で物理アドレスの取得
winsock2 を使用した版。
[ソース]
#include <winsock2.h> #include <iphlpapi.h> #include <vector> #include <iostream> #include <iterator> #include <iomanip> #include <boost/format.hpp> #pragma comment(lib,"iphlpapi.lib") typedef std::vector<unsigned char> mac_address; std::vector<mac_address> get_mac_addresses(){ std::vector<mac_address> result; DWORD bufLen = 0; std::vector<unsigned char> buf; GetAdaptersAddresses(0, 0, 0, 0, &bufLen); if( bufLen ){ buf.resize(bufLen, 0); IP_ADAPTER_ADDRESSES* ptr = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(&buf[0]); DWORD err = GetAdaptersAddresses(0, 0, 0, ptr, &bufLen); if( err == NO_ERROR ){ while(ptr){ if( ptr->PhysicalAddressLength ){ std::vector<BYTE> buffer(ptr->PhysicalAddressLength); std::copy( ptr->PhysicalAddress, ptr->PhysicalAddress + ptr->PhysicalAddressLength, buffer.begin() ); result.push_back(std::move(buffer)); } ptr = ptr->Next; } } } return result; } int main(){ auto mac_addresses = get_mac_addresses(); std::for_each(mac_addresses.begin(), mac_addresses.end(), [](mac_address const& address){ std::for_each(address.begin(), address.end(), [](unsigned char c){ std::cout << std::setw(2) << std::setfill('0') << std::hex << int(c) << "-"; }); std::cout << std::endl; }); return 0; }
[出力例]
00-11-22-33-44-55- 00-11-22-33-44-55- 00-11-22-33-44-55-
Windows だと winsock2 を使用するのが一般的なんですかね。
しかし、msvc2010 でコンパイルしていたけど range-based for が使用できないのがつらすぎる…。