Reliably Retrieve MAC Address(es) with VB

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

When searching for a method to retrieve my own MAC address in VB 6.0, I found only some non-reliable samples that all used the ancient NetBIOS calls. It also seemed to me that all of the authors have just copied from a public available source—the basic code is contained in the MSDN documentation of the Netbios function.

Some of those examples worked more or less, but (as others noted, too) the NetBIOS call does not work reliably. A problem is the adapter enumeration/indexing that may cause several adapter entries existing in the system and the first one often not being the first Ethernet card. Even when retrieving all information blocks and scanning through them, it didn’t work reliably on different systems—especially when the network cable is plugged out—sometimes even no adapter can be found, then.

Those problems made that kind of solution unusable. For example, if You use the MAC address of the network card to license your software, your customer won’t be happy if he can’t use it anymore when the network cable is unplugged!

So, I searched the MSDN for an alternative, and found the documentation of the iphlpapi.dll functions, but found them looking very clumsy to use from within VB 6.0.

When searching through CodeGuru, I found Khalid Shaikh’s article, “Three ways to get your MAC address” (2002/04/15), where he described three ways to retrieve a MAC address and discusses the pros/cons of those methods. This article enforced me to focus on the iphlpapi.dll functions, especially GetAdaptersInfo (the MSDN article can be found here).

Also, J. Guo’s article A New Method to Get MAC/NIC Statistical Information where he showed how to use GetIfTable (the MSDN article can be found here), and a code snippet from a colleague helped me to get some idea to implement my VB code.

During the implementation, I encountered some contradictions in the MSDN docs and some problems with VB’s memory allocation (arrays of user-defined structures are not necessarely laid out contiguously due to internal padding/alignment), but finally got it to work with the tools of the .NET and VB6 debuggers—even with the network cable unplugged—on Windows 2000 and XP.

For testing and my own experience, I implemented both ways, using GetAdaptersInfo and using GetIfTable. The functions deliver different information, they especially differ in that GetAdaptersInfo returns information about physically present adapters and GetIfTable returns information about interfaces present—including the virtual loopback adapter (which has no MAC address, of course).

Screenshot

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read