SendARP未写入mac数组

SendARP not writing out to mac array

本文关键字:mac 数组 SendARP      更新时间:2023-10-16

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函数设置,但它似乎不工作,它不返回一个错误。

转换为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();
}

试试这个:

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