Mirror

Get Computer MAC Address (Views: 100)


Problem/Question/Abstract:

How can you get the computers MAC address?

Answer:

Solve 1:

The following code will allow you to retrieve the MAC address of your computer. It is a close translation of the C++ code found at the Borland Community at:
http://community.borland.com/article/0,1410,26040,00.html

You must include the NB30 unit in your uses clause for this code to work.

Simply call the GetMACAddress routine for the address of the first network adapter installed.

uses
  NB30;

function GetAdapterInfo(Lana: Char): string;
var
  Adapter: TAdapterStatus;
  NCB: TNCB;
begin
  FillChar(NCB, SizeOf(NCB), 0);
  NCB.ncb_command := Char(NCBRESET);
  NCB.ncb_lana_num := Lana;
  if Netbios(@NCB) <> Char(NRC_GOODRET) then
  begin
    Result := 'mac not found';
    Exit;
  end;

  FillChar(NCB, SizeOf(NCB), 0);
  NCB.ncb_command := Char(NCBASTAT);
  NCB.ncb_lana_num := Lana;
  NCB.ncb_callname := '*';

  FillChar(Adapter, SizeOf(Adapter), 0);
  NCB.ncb_buffer := @Adapter;
  NCB.ncb_length := SizeOf(Adapter);
  if Netbios(@NCB) <> Char(NRC_GOODRET) then
  begin
    Result := 'mac not found';
    Exit;
  end;
  Result :=
    IntToHex(Byte(Adapter.adapter_address[0]), 2) + '-' +
    IntToHex(Byte(Adapter.adapter_address[1]), 2) + '-' +
    IntToHex(Byte(Adapter.adapter_address[2]), 2) + '-' +
    IntToHex(Byte(Adapter.adapter_address[3]), 2) + '-' +
    IntToHex(Byte(Adapter.adapter_address[4]), 2) + '-' +
    IntToHex(Byte(Adapter.adapter_address[5]), 2);
end;

function GetMACAddress: string;
var
  AdapterList: TLanaEnum;
  NCB: TNCB;
begin
  FillChar(NCB, SizeOf(NCB), 0);
  NCB.ncb_command := Char(NCBENUM);
  NCB.ncb_buffer := @AdapterList;
  NCB.ncb_length := SizeOf(AdapterList);
  Netbios(@NCB);
  if Byte(AdapterList.length) > 0 then
    Result := GetAdapterInfo(AdapterList.lana[0])
  else
    Result := 'mac not found';
end;


Solve 2:

function TUserInfo.GetPrimaryNicMacAddress(): string;
// Here is a function that we use to get the MAC address.
// It comes from the CoCreateGUID API call.  In W2K
// Microsoft changed the underlying call in CoCreateGUID
// to a random value instead of the MAC address that is
// why the function checks which version of Windows is
// running and then makes the appropriate API call.
type
  TGUID = record
    A, B: word;
    D, M, S: word;
    MAC: array[1..6] of byte;
  end;
var
  UuidCreateFunc: function(var guid: TGUID): HResult; stdcall;
  handle: THandle;
  g: TGUID;
  WinVer: _OSVersionInfoA;
  i: integer;
  ErrCode: HResult;
begin
  WinVer.dwOSVersionInfoSize := sizeof(WinVer);
  getversionex(WinVer);

  handle := LoadLibrary('RPCRT4.DLL');
  if WinVer.dwMajorVersion >= 5 then {Windows 2000 }
    @UuidCreateFunc := GetProcAddress(Handle, 'UuidCreateSequential')
  else
    @UuidCreateFunc := GetProcAddress(Handle, 'UuidCreate');

  UuidCreateFunc(g);
  result := '';
  for i := 1 to 6 do
    result := result + IntToHex(g.MAC[i], 2);
end;

<< Back to main page