Question

Hi can anyone guide me on how to get the NIC addresses on a users computer using C++? I am not entirely sure if this is possible and as a beginner I am not too sure on where to start

Thanks

Was it helpful?

Solution

In windows, you can use the GetAdaptersAddresses function, to retrieve the physical address.

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top