//맥컴퓨터용은(...) 나도 사실 잘모름
#ifdef _WIN32
#include <WinSock.h>
#include <IPHlpApi.h>
#pragma comment(lib, "iphlpapi.lib" )
#else //linux
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#endif
using namespace std;
...
#ifdef _WIN32
string getMacAddress()
{
char strMac[256] = { 0, };
DWORD size = (DWORD)sizeof(PIP_ADAPTER_INFO);
PIP_ADAPTER_INFO Info;
ZeroMemory(&Info, size); //memset((void*)&info, 0, size);
int result = GetAdaptersInfo(Info, (PULONG)&size);
if (result == ERROR_BUFFER_OVERFLOW)
{
Info = (PIP_ADAPTER_INFO)malloc(size);
GetAdaptersInfo(Info, (PULONG)&size);
}
if (!Info)
return string();
sprintf_s(strMac, "%0.2X-%0.2X-%0.2X-%0.2X-%0.2X-%0.2X",
Info->Address[0], Info->Address[1], Info->Address[2], Info->Address[3], Info->Address[4], Info->Address[5]);
return string(strMac);
}
#else //linux version
string getMacAddress()
{
struct ifreq ifr;
struct ifconf ifc;
char buf[1024] = { 0, };
int success = 0;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) { /* handle error*/ };
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
success = 1;
break;
}
}
}
else { /* handle error */ }
}
char mac_address[6] = { 0, };
if (success)
memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
return string(mac_address);
}
#endif
'C++' 카테고리의 다른 글
CMFCProperty 커스터마이징해서 프로퍼티안에 체크박스넣는 클래스인데.. (0) | 2016.12.15 |
---|---|
옛날에 만든 Hex Stream 으로 wireshark세이브 파일 포맷로그저장하는 클래스! (0) | 2016.12.15 |
Raw소켓짤때 헤더(Header)와 프로토콜(Protocol) 작성규칙 (0) | 2016.12.15 |
IPv6헤더 (0) | 2016.12.15 |
체크섬 예제 (0) | 2016.12.15 |