SoFunction
Updated on 2025-04-05

C++ implementation to obtain the native MAC address and IP address

In actual work, the project often needs to obtain the IP address and MAC address of the machine. Here we use two solutions to obtain it.

Get IP and MAC addresses in

To obtain IP, you need to add the "WS2_32.lib" library

Without further ado, the code is as follows

//Get the MAC addressstd::string OnGetLocalMac()
{
	string*   pstrMacs;
	std::string strMac;
	int nMacCount;
	PIP_ADAPTER_INFO pAdapterInfo;  
	PIP_ADAPTER_INFO pAdapterInfo1 = NULL; 
	DWORD AdapterInfoSize;  
	char szMac[33]   =   {0}; 
	DWORD Err;    
	AdapterInfoSize = 0;  
	Err = GetAdaptersInfo(NULL, &AdapterInfoSize);  
	if((Err   !=   0)   &&   (Err   !=   ERROR_BUFFER_OVERFLOW))
	{
		goto err;
	}  
	// Allocate network card information memory	pAdapterInfo = (PIP_ADAPTER_INFO)GlobalAlloc(GPTR, AdapterInfoSize);  
	if(pAdapterInfo == NULL)
	{
		goto err;
	}    
	if(GetAdaptersInfo(pAdapterInfo, &AdapterInfoSize) != 0)
	{  
		GlobalFree(pAdapterInfo);
		goto err;
	}   
	pAdapterInfo1 = pAdapterInfo;
	nMacCount = 0;
	while(pAdapterInfo1)
	{
		nMacCount++;
		pAdapterInfo1= pAdapterInfo1->Next;
	}
	if(nMacCount <= 0)
	{
		GlobalFree(pAdapterInfo);
		goto err;
	}
	pstrMacs = new string[nMacCount];
	pAdapterInfo1 = pAdapterInfo;
	for (int i = 0; i < nMacCount; i++)
	{
		memset(szMac, 0, sizeof(szMac));
		sprintf_s(szMac, 
			32, 
			"%02X:%02X:%02X:%02X:%02X:%02X",
			pAdapterInfo1->Address[0],  
			pAdapterInfo1->Address[1],  
			pAdapterInfo1->Address[2],  
			pAdapterInfo1->Address[3],  
			pAdapterInfo1->Address[4],  
			pAdapterInfo1->Address[5]);
		_strupr_s(szMac,32);
		pstrMacs[i] = szMac;
		pAdapterInfo1 = pAdapterInfo1->Next;
	}
	GlobalFree(pAdapterInfo); 

err:
	//Only the first address is taken here, multiple MAC addresses cannot be confirmed which one is used	strMac = pstrMacs[0];
	return strMac ;
}

//Get IP address#pragma comment(lib, "WS2_32.lib")
std::string OnGetLocalIP()
{

	long lRet = 0;
	char szHostName[256] = {0};
	long lHostNameLen = 256;
	int nRet = 0;
	hostent *phost = NULL;
	std::string strHostIp = "";

//This method cannot be obtained, use the following method instead	//for(int i=0;phost!=NULL&&phost->h_addr_list[i]!=NULL;i++)  
	//{  
	//	char* pszHostIP=inet_ntoa(*(struct in_addr*)phost->h_addr_list[i]);  
	//	strHostIp=pszHostIP;  
	//}
	//Get via gethostname below	WSADATA WSAData;
	if (!WSAStartup(MAKEWORD(2, 0),&WSAData))
	{  
		if(!gethostname(szHostName,sizeof(szHostName)))
		{
			hostent *host=gethostbyname(szHostName);
			if(host!=NULL)
			{
				char* pszHostIP =  inet_ntoa(*(struct in_addr*)*host->h_addr_list);
				strHostIp = pszHostIP;

			}
		}
	}
	return strHostIp;
	
}

2. The above is a commonly used acquisition method in VS C++. If you use Qt, it is easier to obtain it using the Qt library.

// Need to add header file#include <QNetworkInterface>
QString GetMac()
{
    QString strMacAddr = "";
    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();//Get all network card information    for (int i = 0; i < (); i++)
    {
        QNetworkInterface iface = (i);
        if ( ().testFlag(QNetworkInterface::IsUp) && ().testFlag(QNetworkInterface::IsRunning) && !().testFlag(QNetworkInterface::IsLoopBack))
        {
            for (int j=0; j<().count(); j++)
            {
                strMacAddr = ();
                i = (); //Breaking out of the outer loop                break;
            }
        }
    }

    return strMacAddr;
}

QString GetIP()
{
    QString strIPAddr = "";
    foreach (QHostAddress ptr , QNetworkInterface::allAddresses())
    {
        if(() == QAbstractSocket::IPv4Protocol){// Get the ipv4 address            if(!()){  // Filter local loopback 127.0.0.1                strIPAddr = ();
                break;
            }
        }
    }
    return strIPAddr;
}

The above is the method to obtain native IP and MAC in VS and Qt.

This is the article about C++ realizing the acquisition of native MAC address and IP address. For more related C++ to obtain native MAC address, please search for my previous article or continue browsing the following related articles. I hope everyone will support me in the future!