We are using the following code for retrieving active MAC address of a windows pc.
private static string macId()
{
return identifier(\"Win32_NetworkAdapt
I had to write something similar a little while ago because I was using a number of hardware parameters for "activation" of my software.
Have a look at, DeviceIoControl & OID_802_3_PERMANENT_ADDRESS. Its a lot of interop code (my class for handling it is approximatley 200 lines), but it gets me the hardware code guaranteed.
Some code snippets to get you going,
private const uint IOCTL_NDIS_QUERY_GLOBAL_STATS = 0x170002;
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
ref int InBuffer,
int nInBufferSize,
byte[] OutBuffer,
int nOutBufferSize,
out int pBytesReturned,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern SafeFileHandle CreateFile(
string lpFileName,
EFileAccess dwDesiredAccess,
EFileShare dwShareMode,
IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
[Flags]
internal enum EFileAccess : uint
{
Delete = 0x10000,
ReadControl = 0x20000,
WriteDAC = 0x40000,
WriteOwner = 0x80000,
Synchronize = 0x100000,
StandardRightsRequired = 0xF0000,
StandardRightsRead = ReadControl,
StandardRightsWrite = ReadControl,
StandardRightsExecute = ReadControl,
StandardRightsAll = 0x1F0000,
SpecificRightsAll = 0xFFFF,
AccessSystemSecurity = 0x1000000, // AccessSystemAcl access type
MaximumAllowed = 0x2000000, // MaximumAllowed access type
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000
}
// Open a file handle to the interface
using (SafeFileHandle handle = FileInterop.CreateFile(deviceName,
FileInterop.EFileAccess.GenericRead | FileInterop.EFileAccess.GenericWrite,
0, IntPtr.Zero, FileInterop.ECreationDisposition.OpenExisting,
0, IntPtr.Zero))
{
int bytesReturned;
// Set the OID to query the permanent address
// http://msdn.microsoft.com/en-us/library/windows/hardware/ff569074(v=vs.85).aspx
int OID_802_3_PERMANENT_ADDRESS = 0x01010101;
// Array to capture the mac address
var address = new byte[6];
if (DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS,
ref OID_802_3_PERMANENT_ADDRESS, sizeof(uint),
address, 6, out bytesReturned, IntPtr.Zero))
{
// Attempt to parse the MAC address into a string
// any exceptions will be passed onto the caller
return BitConverter.ToString(address, 0, 6);
}
}