SendARP没有写出到mac数组

时间:2013-06-04 17:47:59

标签: c++ winapi network-programming embedded

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];
            }
        }
    }
}

我已尝试过多种方法让SendAdP设置MacAddr,但它似乎不起作用,并且不会返回错误。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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();
}