<<

Winsock Programmer's FAQ
Example: How to Get the Ethernet MAC Address, RPC Method

>>

This example shows you how to use the RPC API to retrieve the MAC addresses of at least one of the network adapters in a system. There are two weaknesses to this approach. The first is that it is not guaranteed to work. All it does is rely on the way UUIDs are defined by RPC, which is that the last six bytes are derived from the hardware address of the machine's network adapter. The second, potentially more important problem is that this won't work if there is more than one Ethernet adapter in the system. I've not tried it, but I suspect that this program will return the address of the "first" Ethernet adapter. If you need the second as well, better try the NetBIOS method.

On the other hand, this method has several advantages. First, it does not require anything extra to be installed on the user's machine: RPC comes with all Win32 variants. Second, it's a lot smaller, codewise, than the NetBIOS method. Third, it doesn't have the 00:00:00:00:00:00 problem of the NetBIOS code. That could probably be fixed, but that would make the second advantage (code size) even more obvious.

Nevertheless, this is in fact a demented kludge. Caveat hacker.


getmac-rpc.cpp

// Visual C++ 5.0:  cl -GX getmac-rpc.cpp rpcrt4.lib
// Borland C++ 5.0: bcc32 getmac-rpc.cpp

#include <rpc.h>
#include <iostream>

#ifdef _MSC_VER
using namespace std;
#endif

int main()
{
    cout << "MAC address is: ";

    // Ask RPC to create a UUID for us.  If this machine has an Ethernet
    // adapter, the last six bytes of the UUID (bytes 2-7 inclusive in
    // the Data4 element) should be the MAC address of the local
    // Ethernet adapter.
    UUID uuid;
    UuidCreate(&uuid);

    // Spit the address out
    for (int i = 2; i < 8; ++i) {
        cout << hex;
        cout.fill('0');
        cout.width(2);
        cout << int (uuid.Data4[i]);
        if (i < 7) {
            cout << ":";
        }
    }
    cout << endl;

    return 0;
}

<< Get MAC Address Get MAC Address, SNMP Method >>
Last modified on 29 April 2000 at 15:52 UTC-7 Please send corrections to tangent@cyberport.com.
< Go to the main FAQ page
<< Go to my Programming pages
<<< Go to my Home Page