ARP is used to convert the IP address and MAC address. It specifies the IP address in the LAN where the MAC address is to be obtained in the ARP packet and then sends it to the LAN, the machine with the specified IP address receives and returns an ARP packet, and specifies its MAC address in the returned packet.
In this way, the Mac is obtained. The MAC address of the local machine can also be obtained in this way.
The following is code implementation. For convenience, I directly used the sendarp function, instead of encapsulating ARP packets at the underlying layer.
/*
* Obtain the MAC address with the IP address ipdst in the LAN and save the result in the bydstmac parameter.
* Whether the return operation is successful
*/
Template <int nsize>
Bool getmacaddress (ipaddr ipdst, byte (& bydstmac) [nsize])
{
Assert (nsize> = 6 );
Memset (bydstmac, 0, nsize );
DWORD dwbufferlen = nsize;
DWORD dwret =: sendarp (ipdst, 0, (Pulong) & bydstmac, & dwbufferlen );
Return dwret = no_error;
}
This function is used as follows:
// Example
Byte bydstmac [6];
If (getmacaddress (: inet_addr ("192.168.8.132"), bydstmac ))
{
Cstring Strmac;
Strmac. format (_ T ("%. 2X-%. 2X-%. 2X-%. 2X-%. 2X-%. 2x "), bydstmac [0], bydstmac [1], bydstmac [2], bydstmac [3], bydstmac [4], bydstmac [5]);
Afxmessagebox (Strmac );
}