Prints MAC addresses for Ethernet type devices
6
Code snippet that prints MAC addresses for Ethernet type devices.
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Iphlpapi.h>
// Declare and initialize variables
DWORD dwSize = 0;
DWORD dwRetVal = 0;
DWORD i;
DWORD j;
MIB_IFROW ifRow;
PMIB_IFTABLE ifTable;
// Allocate memory for our pointers
ifTable = (MIB_IFTABLE*) malloc(sizeof(MIB_IFTABLE));
// Make an initial call to GetIfTable to get the
// necessary size into the dwSize variable
if (GetIfTable(ifTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
free(ifTable);
ifTable = (MIB_IFTABLE *) malloc (dwSize);
}
// Make a second call to GetIfTable to get the
// actual data we want
if ((dwRetVal = GetIfTable(ifTable, &dwSize, 0)) == NO_ERROR) {
printf("\tNumber of entries: %ld\n", ifTable->dwNumEntries);
}
else {
printf("\tGetIfTable failed.\n");
}
// Step through the MIB-II table and print only Ethernet entries.
for (i = 0; i < ifTable->dwNumEntries; ++i)
{
ifRow = ifTable->table[i];
if(ifRow.dwType == MIB_IF_TYPE_ETHERNET)
{
// Two lines of output:
// Ethernet device: <description>
// MAC Address: XX:XX:XX:XX:XX:XX
printf("\tEthernet device: %s\n", ifRow.bDescr);
printf("\tMAC Address: ");
printf("%02X", ifRow.bPhysAddr[0]);
for (j = 1; j < ifRow.dwPhysAddrLen; ++j)
printf(":%02X", ifRow.bPhysAddr[j]);
printf("\n\n");
}
}
free(ifTable);






But this comment is mostly about crappy Microsoft "engineering", if you want to glorify it with that term. What kind of crap-hole design is it to make you call the same function twice to get it sized correctly?
The correct signature for this function would have been:
GetIfTable(MIB_IFTABLE **, DWORD *, int)
instead of:
GetIfTable(MIB_IFTABLE *, DWORD *, int)
Then, the function, which _knows_ how much it needs to return, can put the data wherever it wants, and change the provided pointer value (notice the double-dereference in 'MIB_IFTABLE **'). But nooooo . . . that would make too much sense! (Being the standard C/C++ idiom for such procedures . . . )
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
Don't worry, I didn't vote it down!
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
Bobby R Ward
---------------------
bobbyrward@gmail.com