0

嗨,谁能指导我如何使用 C++ 在用户计算机上获取 NIC 地址?我不完全确定这是否可行,作为初学者,我不太确定从哪里开始

谢谢

4

1 回答 1

1

在 Windows 中,您可以使用 GetAdaptersAddresses 函数来检索物理地址。

std::string ConvertPhysicalAddressToString(BYTE* p_Byte, int iSize)
{
    string strRetValue;

    char cAux[3];
    for(int i=0; i<iSize; i++)
    {
        sprintf_s(cAux,"%02X", p_Byte[i]);
        strRetValue.append(cAux);
        if(i < (iSize - 1))
            strRetValue.append("-");
    }

    return strRetValue;
}

void GetEthernetDevices(std::vector<std::string> &vPhysicalAddress)
{       
    // Call the Function with 0 Buffer to know the size of the buffer required 
    unsigned long ulLen = 0;
    IP_ADAPTER_ADDRESSES* p_adapAddress = NULL;
    if(GetAdaptersAddresses(AF_INET, 0, NULL, p_adapAddress,&ulLen) == ERROR_BUFFER_OVERFLOW)
    {
        p_adapAddress = (PIP_ADAPTER_ADDRESSES)malloc(ulLen);
        if(p_adapAddress)
        {
            DWORD dwRetValue = GetAdaptersAddresses(AF_INET, 0, NULL, p_adapAddress,&ulLen);
            if(dwRetValue == NO_ERROR)
            {               
                IP_ADAPTER_ADDRESSES* p_adapAddressAux = p_adapAddress;
                do
                {
                    // Only Ethernet
                    if(p_adapAddressAux->IfType == IF_TYPE_ETHERNET_CSMACD)                 
                        vPhysicalAddress.push_back(ConvertPhysicalAddressToString(p_adapAddressAux->PhysicalAddress, p_adapAddressAux->PhysicalAddressLength));

                    p_adapAddressAux = p_adapAddressAux->Next;
                }
                while(p_adapAddressAux != NULL);                        
            }
            free(p_adapAddress);
        }
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<std::string> vPhysicalAddress;
    GetEthernetDevices(vPhysicalAddress);
}
于 2012-10-26T14:58:43.567 回答