Category Archives: The Windows platform

MAC Address on Vista in C

Just learnt this (I’m a UNIX guy, so give me a break) but to find my MAC address on Vista I can use this command

$ getmac

Physical Address    Transport Name
===================
Disabled            Disconnected
Disabled            Disconnected
00-1B-77-52-B1-35   \Device\Tcpip_{71505A5B-B296-4FD7-8B61-A869D8AC6AEB}

Handy, but I wanted it in code. And so, sticking to my handy dandy MinGW

#include <winsock2.h>
#include <iphlpapi.h>
#include <assert.h>
#include "stdio.h"

int main(int argc, const char *argv[])
{
	IP_ADAPTER_INFO AdapterInfo[2];
  	DWORD dwBufLen = sizeof(AdapterInfo);
  	DWORD dwStatus = GetAdaptersInfo(AdapterInfo, &dwBufLen);
  	assert(dwStatus == ERROR_SUCCESS);
  	PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;

	printf("\tAdapter Name: \t%s\n", pAdapterInfo->AdapterName);

	printf("\tAdapter Addr: \t");
	for (int i = 0; i < pAdapterInfo->AddressLength; i++) {
	  if (i == (pAdapterInfo->AddressLength - 1))
	    printf("%.2X\n", (int) pAdapterInfo->Address[i]);
	  else
	    printf("%.2X-", (int) pAdapterInfo->Address[i]);
	}

	return 0;
}

Compiled by

$ gcc -std=c99 macAddr.c -liphlpapi

and giving

$ a.exe
        Adapter Name:   {71505A5B-B296-4FD7-8B61-A869D8AC6AEB}
        Adapter Addr:   00-1B-77-52-B1-35

Yes, very handy. And all because I wanted gethostid and it’s not there on Windows or with MinGW

#include <unistd.h> // long gethostid(void) - NOPE

Now I can go to sleep and have sweet dreams :-)