I\'d like to be able to read the mac address from the first active network adapter using VB.net or C# (using .NET 3.5 SP1) for a winform application
For anyone using the more limited Compact Framework (.NET v2.0 CF) the following code works on both Windows CE 5.0 and CE 6.0 (reading just the adaptor name, but search for "typedef struct _IP_ADAPTER_INFO" on MSDN to get the full definition of the structure returned):
private const int MAX_ADAPTER_NAME_LENGTH = 256;
[DllImport ("iphlpapi.dll", SetLastError = true)]
private static extern int GetAdaptersInfo(byte[] abyAdaptor, ref int nSize);
// ...
private static string m_szAdaptorName = "DM9CE1";
// ...
private void GetNetworkAdaptorName()
{
// The initial call is to determine the size of the memory required. This will fail
// with the error code "111" which is defined by MSDN to be "ERROR_BUFFER_OVERFLOW".
// The structure size should be 640 bytes per adaptor.
int nSize = 0;
int nReturn = GetAdaptersInfo(null, ref nSize);
// Allocate memory and get data
byte[] abyAdapatorInfo = new byte[nSize];
nReturn = GetAdaptersInfo(abyAdapatorInfo, ref nSize);
if (nReturn == 0)
{
// Find the start and end bytes of the name in the returned structure
int nStartNamePos = 8;
int nEndNamePos = 8;
while ((abyAdapatorInfo[nEndNamePos] != 0) &&
((nEndNamePos - nStartNamePos) < MAX_ADAPTER_NAME_LENGTH))
{
// Another character in the name
nEndNamePos++;
}
// Convert the name from a byte array into a string
m_szAdaptorName = Encoding.UTF8.GetString(
abyAdapatorInfo, nStartNamePos, (nEndNamePos - nStartNamePos));
}
else
{
// Failed? Use a hard-coded network adaptor name.
m_szAdaptorName = "DM9CE1";
}
}