0

SendARP 没有设置我的 mac 数组,所以同样当我尝试将 mac 数组转换为 BYTE 以将其转换为人类可读时,它也会在其中获取随机字符。memset 似乎也没有使 MacAddr 为 0!

std::wstring GetMacAddress(IPAddr destip)
{
    DWORD ret;
    ULONG MacAddr[2] = {0};  //initialize instead of memset
    ULONG PhyAddrLen = 6;  /* default to length of six bytes */
    unsigned char mac[6]; 

    //memset(MacAddr, 0, sizeof(MacAddr));  //MacAddr doesn't get set to 0!
    //Send an arp packet
    ret = SendARP(destip , 0, MacAddr , &PhyAddrLen); //MacAddr stays

    //Prepare the mac address
    if (ret == NO_ERROR)
    {
        BYTE *bMacAddr = (BYTE *) & MacAddr;

        if(PhyAddrLen)
        {
            for (int i = 0; i < (int) PhyAddrLen; i++)
            {
                mac[i] = (char)bMacAddr[i];
            }
        }
    }
}

我已经尝试了多种方法让 MacAddr 由 SendARP 函数设置,但它似乎不起作用并且它不返回错误。

4

2 回答 2

0

尝试这个:

static const wchar_t *HexChars = L"0123456789ABCDEF";

std::wstring GetMacAddress(IPAddr destip)
{
    DWORD ret;
    BYTE MacAddr[sizeof(ULONG)*2];
    ULONG PhyAddrLen = sizeof(MacAddr);
    std::wstring MacAddrStr;

    ret = SendARP(destip, 0, (PULONG)MacAddr, &PhyAddrLen);
    if ((ret == NO_ERROR) && (PhyAddrLen != 0))
    {
        MacAddrStr.resize((PhyAddrLen * 2) + (PhyAddrLen-1));

        MacAddrStr[0] = HexChars[(MacAddr[0] & 0xF0) >> 4];
        MacAddrStr[1] = HexChars[MacAddr[0] & 0x0F];

        for (ULONG i = 1, j = 2; i < PhyAddrLen; ++i, j += 3)
        {
            MacAddrStr[j+0] = L':';
            MacAddrStr[j+1] = HexChars[(MacAddr[i] & 0xF0) >> 4];
            MacAddrStr[j+2] = HexChars[MacAddr[i] & 0x0F];
        }
    }

    return MacAddrStr;
}
于 2013-06-04T19:28:46.627 回答
0

转换为char不会转换为文本表示。如果要转换为文本表示,一种选择是使用std::wstringstream

#include <sstream>
#include <string>
#include <iomanip>

std::wstring GetMacAddress(IPAddr destip)
{
    // ... snip ...

    std::wstringstream  out;
    for (int i = 0; i < (int) PhyAddrLen; i++)
    {
        out << std::setw(2) << std::setfill(L'0') << bMacAddr[i];
    }

    return out.str();
}
于 2013-06-04T19:30:15.710 回答