Created
October 25, 2021 03:21
-
-
Save bphucc/992a71bafdee375d6d8f69e9277d6a05 to your computer and use it in GitHub Desktop.
Get local device's MAC address.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#include <stdio.h> | |
#pragma comment(lib, "WS2_32") | |
#include <iphlpapi.h> | |
#pragma comment(lib, "iphlpapi") | |
#define IP_LOCALHOST 0x0100007F | |
void print_ip(DWORD nAddr) | |
{ | |
printf("%d.%d.%d.%d\n", nAddr & 0x000000FF, (nAddr & 0x0000FF00) >> 8, (nAddr & 0x00FF0000) >> 16, (nAddr & 0xFF000000) >> 24); | |
} | |
int main() | |
{ | |
ULONG nSize = 0; | |
MIB_IPADDRTABLE * ip_table = NULL; | |
if (GetIpAddrTable(ip_table, &nSize, 0) == ERROR_INSUFFICIENT_BUFFER) | |
{ | |
ip_table = (MIB_IPADDRTABLE *) malloc(nSize); | |
if (GetIpAddrTable(ip_table, &nSize, 0) == NO_ERROR) | |
{ | |
for (int i = 0; i < ip_table->dwNumEntries; ++i) | |
{ | |
print_ip(ip_table->table[i].dwAddr); | |
if (IP_LOCALHOST != ip_table->table[i].dwAddr) | |
{ | |
MIB_IFROW iInfo; | |
BYTE byMAC[6] = { 0, 0, 0, 0, 0, 0 }; | |
memset(&iInfo, 0, sizeof(MIB_IFROW)); | |
iInfo.dwIndex = ip_table->table[i].dwIndex; | |
GetIfEntry(&iInfo); | |
if (MIB_IF_TYPE_ETHERNET == iInfo.dwType) | |
{ | |
memcpy(&byMAC, iInfo.bPhysAddr, iInfo.dwPhysAddrLen); | |
printf("MAC Address = %02x-%02x-%02x-%02x-%02x-%02x\n", byMAC[0],byMAC[1],byMAC[2], byMAC[3],byMAC[4],byMAC[5]); | |
} | |
} | |
} | |
} | |
else | |
printf("unable to read IP table from system\n"); | |
free(ip_table); | |
} | |
else | |
printf("unable to determine number of entries in IP table\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment