Prints MAC addresses for Ethernet type devices





6
Date Submitted Mon. Mar. 13th, 2006 11:49 AM
Revision 1 of 1
Coder mattrmiller
Tags "MAC Address" | C | Devices | Ethernet
Comments 3 comments
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);
 

Matthew R. Miller

www.bluecreststudios.com
=================
Matthew R. Miller

http://bluecreststudios.com
http://www.codeandcoffee.com

Comments

Comments Ummm . . .
Fri. Sep. 22nd, 2006 12:38 AM    Scripter sehrgut
Comments Windows tag . . .
Mon. Oct. 9th, 2006 10:44 AM    Scripter sehrgut
Comments Meant to vote up
Wed. Aug. 9th, 2006 6:15 AM    Helper bobbyrward

Voting