get the MAC of an IP address

Gets the MAC address given the IP address. If the IP address does not exist, returns "".

Download macaddress.zip

Synopsis:

macaddress.cpp
macaddress.h
macaddress_test.cpp


macaddress.cpp

Synopsis
#include <string>
using namespace std;
#include <windows.h>
#include <iphlpapi.h>
#include "macaddress.h"

// Link with ws2_32.lib and iphlpapi.lib
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")

static IPAddr ToIpAddress(const string& ipaddress)
  {
  return inet_addr(ipaddress.c_str());
  }

string MacAddress::GetFrom(const string& ipaddress)
  {
  if (ipaddress == "") return "";
  return GetMac(ipaddress);
  }

string MacAddress::GetMac(const string& ipaddress)
  {
  mMacLen = cMACLen;
  memset(mMacBuffer, 0xff, sizeof(mMacBuffer));
  if (S_OK  == ::SendARP(ToIpAddress(ipaddress), 0, (ULONG*)mMacBuffer, &mMacLen))
    return ToString();
  return "";
  }

string MacAddress::ToString()
  {
  char szMac[50];
  size_t j = 0;
  char* sep = "";
  for (ULONG i = 0; i < mMacLen; ++i) 
    {
    if (i == 1) sep = "-";
    j += sprintf (szMac + j, "%s%02.2X", sep, (BYTE) mMacBuffer[i]);
    }
  return string(szMac);
  }


macaddress.h

Synopsis
#pragma once
#include <string>
using std::string;

class MacAddress
  {
  public:
    string GetFrom(const string& ipaddress);
  private:
    enum {cMACLen = 6};
    char mMacBuffer[cMACLen];
    ULONG mMacLen;

    string GetMac(const string& ipaddress);
    string ToString();
  };

macaddress_test.cpp

Synopsis
#include "utx.h"

#include "macaddress.h"
namespace macaddress_test
  {
  TEST(empty)
    {
    MacAddress ma;
    utxassert(ma.GetFrom(""), "");
    }
  TEST(normal_local)
    {
    MacAddress ma;
    utxassert(ma.GetFrom("192.168.123.100"), "00-01-03-D2-D6-A9");
    }
  TEST(notfound)
    {
    MacAddress ma;
    utxassert(ma.GetFrom("192.168.123.127"), "");
    }
  TEST(normal_remote)
    {
    MacAddress ma;
    utxassert(ma.GetFrom("192.168.123.254"), "00-50-18-13-C8-B0");
    }
  }






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001-2010