#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);
}
|
#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");
}
}
|