Network Programming programmers have to deal with MAC addresses. To some extent, this 128bit digital string represents the uniqueness of the machine, therefore, MAC addresses are generally used as the standard for statistics. The following describes two ways to obtain the MAC address of a local machine. 1. Obtain the MAC address by requesting the NetBIOS service; 2. Obtain the MAC address through the iphelpapi. The first method requires the local machine to enable the NetBIOS service. Because some machines have disabled this service, the retrieval may fail. I personally recommend the second method.
1. Obtain the MAC address by requesting the NetBIOS service. Use the library netapi32.lib
Struct astat
{
Adapter_status adapt;
Name_buffer namebuff [30];
};
Bool getmacbynetbios (unsigned char * Mac)
{
If (! Mac)
{
Return false;
}
Astat adapter;
NCB;
Memset (& NCB, 0, sizeof (NCB ));
NCB. ncb_command = ncbreset;
NCB. ncb_lana_num = 0;
NetBIOS (& NCB );
Memset (& NCB, 0, sizeof (NCB ));
NCB. ncb_command = ncbastat;
NCB. ncb_lana_num = 0;
Strcpy (char *) NCB. ncb_callname ,"*");
NCB. ncb_buffer = (unsigned char *) & adapter;
NCB. ncb_length = sizeof (adapter );
If (NetBIOS (& NCB) = 0)
{
Memcpy (MAC, Adapter. Adapt. adapter_address, 6 );
Return true;
}
Else
{
Memset (MAC, 0, 6 );
Return false;
}
}
2. Obtain it using the iphelpapi and use the iphlpapi. Lib library.
# Include <iphlpapi. h>
Bool getmacbyiphelp (unsigned char * Mac)
{
If (! Mac)
{
Return false;
}
Ulong uloutbuflen = 0;
If (getadaptersinfo (null, & uloutbuflen) = error_buffer_overflow)
{
Int ndivisor = sizeof (ip_adapter_info );
If (sizeof (time_t) = 8)
Ndivisor-= 8;
Int ncount = uloutbuflen/ndivisor;
Pip_adapter_info padapterinfo = new ip_adapter_info [ncount];
If (getadaptersinfo (padapterinfo, & uloutbuflen )! = Error_success)
{
Delete [] padapterinfo;
Memset (MAC, 0, 6 );
Return false;
}
Else
{
Memcpy (MAC, padapterinfo-> address, 6 );
Delete [] padapterinfo;
Return true;
}
}
Else
{
Memset (MAC, 0, 6 );
Return false;
}
}
The usage of the above two functions is as follows:
Void main (void)
{
Unsigned char Mac [6];
Getmacbynetbios (MAC );
Printf ("get Mac by NETBIOS: % 02x % 02x % 02x % 02x % 02x % 02x/N", Mac [0], Mac [1], Mac [2], mac [3], Mac [4], Mac [5]);
Getmacbynetbios (MAC );
Printf ("get Mac by iphelp: % 02x % 02x % 02x % 02x % 02x % 02x/N", Mac [0], Mac [1], Mac [2], mac [3], Mac [4], Mac [5]);
}