How to get the MAC address in WINDOWS ? lazarus / 21-General ---------------------------------------------------------------------- the_magik_mushroom · 2024-08-09 21:04 Hi everyone, simple question but how to simply and quickly get the mac address in win7/10/11? the only way I managed with chatgpt is kind of dirty (an invisible cmd line with getmac and scrapping the result): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses: Process; function MAC: string; //GetMACAddressvar  AProcess: TProcess;  AStringList: TStringList;  I: Integer;  OutputLine: string;begin  Result := '';  AProcess := TProcess.Create(nil);  AStringList := TStringList.Create;  try    AProcess.Executable := 'getmac';    AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole];    AProcess.Execute;    AStringList.LoadFromStream(AProcess.Output);     for I := 0 to AStringList.Count - 1 do    begin      OutputLine := AStringList[I];    // Assuming the MAC address is in the second column, adjust the parsing as needed      if Pos('-', OutputLine) > 0 then      begin      Result := Trim(Copy(OutputLine, 1, Pos(' ', OutputLine) - 1));      Break;      end;    end;  finally    AProcess.Free;    AStringList.Free;  end;end;  It's slow (~0.4 sec on my system) anyway to get it faster? thanks ---------------------------------------------------------------------- dsiders · 2024-08-09 22:27 Quote from: the_magik_mushroom on August 09, 2024, 11:04:41 pmHi everyone, simple question but how to simply and quickly get the mac address in win7/10/11? the only way I managed with chatgpt is kind of dirty (an invisible cmd line with getmac and scrapping the result): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses: Process; function MAC: string; //GetMACAddressvar  AProcess: TProcess;  AStringList: TStringList;  I: Integer;  OutputLine: string;begin  Result := '';  AProcess := TProcess.Create(nil);  AStringList := TStringList.Create;  try    AProcess.Executable := 'getmac';    AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole];    AProcess.Execute;    AStringList.LoadFromStream(AProcess.Output);     for I := 0 to AStringList.Count - 1 do    begin      OutputLine := AStringList[I];    // Assuming the MAC address is in the second column, adjust the parsing as needed      if Pos('-', OutputLine) > 0 then      begin      Result := Trim(Copy(OutputLine, 1, Pos(' ', OutputLine) - 1));      Break;      end;    end;  finally    AProcess.Free;    AStringList.Free;  end;end;  It's slow (~0.4 sec on my system) anyway to get it faster? thanks  Did you try using GetAdaptersAddresses in the Windows IpHlp API? https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf- iphlpapi-getadaptersaddresses Wrappers in packages/winunit-jedi/src/jwaiphlpapi.pas. Should be faster than spawn a process and parsing the results. ---------------------------------------------------------------------- bobby100 · 2024-08-09 23:56 I am using WMI: https://forum.lazarus.freepascal.org/index.php/topic,57807.0.html ---------------------------------------------------------------------- silvercoder70 · 2024-08-10 02:00 This code should (?) work and uses IPHlpAPI DLL... (I know it works in Delphi ) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i //--------- ---------------------------------------------------------------------f unction SendARP(DestIP: DWORD; SrcIP: DWORD; pMacAddr: PDWORD; varPhyAddrLen: DWORD): DWORD; stdcall; external 'IPHlpAPI.DLL'; //---- ---------------------------------------------------------------------- ----function GetRemoteMACAddress2(SourceIp, DestIP: string; var AMacAddr: string): DWORD;type  TInfo = array[0..7] of BYTE;var  dwSourceIP: DWORD;  dwTargetIP: DWORD;  dwMacAddress: array[0..1] of DWORD;  dwMacLen: DWORD;  dwResult: DWORD;  X: TInfo;begin  dwSourceIP := 0;  if SourceIp <> '' then  begin    dwSourceIP := Inet_Addr(PChar(SourceIp));  end;  dwTargetIP := Inet_Addr(PChar(DestIP));  dwMacLen := 6;  dwResult := SendARP(dwTargetIP, dwSourceIP, @dwMacAddress[0], dwMacLen);  result := dwResult;   if dwResult = NO_ERROR then  begin    X := TInfo(dwMacAddress);    AMacAddr := Format('%.2x-%.2x-%.2x-%.2x-%.2x-%.2x',      [X[0], X[1], X[2], X[3], X[4], X[5]]);  end  else  begin    AMacAddr := '';  end;end; ---------------------------------------------------------------------- bpranoto · 2024-08-10 03:04 This is my network interfaces query for MAC address and IPv4 Address, it works on linux and windows. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit network_interfaces; {$mode ObjFPC}{$H+} interface uses  Classes, SysUtils,Generics.collections,Generics.defaults,variants  {$IFDEF UNIX}  ,BaseUnix,Sockets,streamex  {$ENDIF}   {$IFDEF WINDOWS}  ,Windows, Winsock,Registry,ComObj,ActiveX  {$ENDIF}   ; type  TNetworkInterfaceRecord=record    Name:String;    Index:Integer;    IPv4:String;    MacAddress:String;  end;  TANetworkInterfaceRecord=array of TNetworkInterfaceRecord;   { TNetworkInterfaces }   TNetworkInterfaces=class(TObject)  private    FInterfaces:TANetworkInterfaceRecord;    function GetInterfaces:TANetworkInterfaceRecord;    {$IFDEF UNIX}    function GetIPV4Address( IfName:String):String;    {$ENDIF}     {$IFDEF WINDOWS}    procedure SetWMIQuery(out SWbemLocator: olevariant;out WMIService: olevariant);    function GetIPV4Address(Index:UInt32):TStringArray;    {$ENDIF}  public    constructor Create;    property Interfaces:TANetworkInterfaceRecord read FInterfaces;  end;   { TNetworkInterfaceComparer }   TNetworkInterfaceComparer=class(TInterfacedObject,specialize IComparer)  public    function Compare(constref NIC1,NIC2: TNetworkInterfaceRecord): Integer;  end;  implementation  {$IFDEF UNIX}const NETDEV_FILE='/proc/net/dev';  NETDEV_INFO_DIR='/sys/class/net/'; SIOCGIFADDR = $8915; IFNAMSIZ = 16; // Adjust if necessary type  TIfReq = packed record    ifr_name: array[0..IFNAMSIZ-1] of char;    ifr_addr: sockaddr_in;  end;   TIPAddress = array[0..3] of Byte; function inet_ntoa( IPv4:cuint32):String;var  AParam:cuint32;  IPAddress:TIPAddress absolute AParam;begin  AParam:=IPV4;  Result:=IntToStr(IPAddress[0]) + '.' + IntToStr(IPAddress[1]) + '.' +      IntToStr(IPAddress[2]) + '.' + IntToStr(IPAddress[3]);end;{$ENDIF} {$IFDEF WINDOWS}const  wbemFlagForwardOnly = $00000020;{$ENDIF}   { TNetworkInterfaceComparer } function TNetworkInterfaceComparer.Compare(constref NIC1,  NIC2: TNetworkInterfaceRecord): Integer;begin  if NIC1.Index;  i,j:Integer;  {$IFDEF UNIX}  NetDev:TFileStream;  Reader:TStreamReader;  Line:String;  DevDir:String;  IfIndex:String;  IfName:String;{$ENDIF} {$IFDEF WINDOWS}  SWbemLocator: olevariant;  WMIService: olevariant;  QueryStr:String;  WbemObjectSet: olevariant;  WbemObject: olevariant;  oEnum: IEnumvariant;  iValue: longword;  IPV4Array:TStringArray; {$ENDIF}  begin  // Ensure empty result  Result:=TANetworkInterfaceRecord.Create;   {$IFDEF UNIX}    // Get Active interfaces from /proc/net/dev    Reader:=NIL;    NetDev:=TFileStream.Create(NETDEV_FILE,fmOpenRead);    try      Reader:=TStreamReader.Create(NetDev);      while not Reader.Eof do begin        Line:=Reader.ReadLine;        // Interface lines have :      i:=Pos(':',Line);        if i>0 then begin           // Get interface name          ifName:=Trim(Copy(Line,1,i-1));           // Save it to the result          i:=Length(Result);SetLength(Result,i+1);          Result[i].Name:=IfName;        end;      end;       // Read the info from /sys/class/net      for i:=0 to Length(Result)-1 do begin        DevDir:=IncludeTrailingPathDelimiter(NETDEV_INFO_DIR+Result[i].Name);        // Read Index        NetDev.Free;NetDev:=NIL;        NetDev:=TFileStream.Create(DevDir+'ifindex',fmOpenRead);        Reader.Free;Reader:=NIL;        Reader:=TStreamReader.Create(NetDev);        //        IfIndex:=Reader.ReadLine;        Result[i].Index:=StrToInt(IfIndex);         // Read MacAddress        NetDev.Free;NetDev:=NIL;        NetDev:=TFileStream.Create(DevDir+'address',fmOpenRead);        Reader.Free;Reader:=NIL;        Reader:=TStreamReader.Create(NetDev);        Result[i].MacAddress:=Reader.ReadLine;          // Read IP address        Result[i].IPv4:=Self.GetIPV4Address(Result[i].Name);    end;     finally      Reader.Free;      NetDev.Free;    end;  {$ENDIF}   {$IFDEF WINDOWS}  Self.SetWMIQuery(SWbemLocator,WMIService);   // QueryStr:='SELECT * FROM Win32_NetworkAdapter WHERE  Manufacturer != ''Microsoft'' AND NOT PNPDeviceID LIKE ''ROOT\\%''';  QueryStr:='SELECT * FROM Win32_NetworkAdapter WHERE  Manufacturer != ''Microsoft''';   WbemObjectSet := WMIService.ExecQuery( QueryStr,'WQL', wbemFlagForwardOnly);  oEnum := IUnknown(WbemObjectSet._NewEnum) as IEnumVariant;   while oEnum.Next(1, WbemObject, iValue) = 0 do begin  i:=Length(Result);SetLength(Result,i+1);     // WINDOWS XP doesn't have InterfaceObject    if Win32MajorVersion>5 then begin      if not VarIsNull(WbemObject.InterfaceIndex) then begin        Result[i].Index:=WbemObject.InterfaceIndex;      end;    end    else begin      // WINDOWS XP use DeviceID      if not VarIsNull(WbemObject.Index) then begin        Result[i].Index:=WbemObject.DeviceID;      end;    end;     if not VarIsNull(WbemObject.Name) then begin      Result[i].Name:=WbemObject.Name;    end;     if not VarIsNull(WbemObject.MACAddress) then begin      Result[i].MacAddress := WbemObject.MACAddress;    end;     if not VarIsNull(WbemObject.Description) then begin       // Get IPv4, one adapter can have more than 1 address      IPV4Array :=Self.GetIPV4Address(WbemObject.DeviceID);      if Length(IPV4Array)>0 then begin        Result[i].IPv4:=IPV4Array[0];       // if there are more than 1 ip, make additional entry        if Length(IPV4Array) > 1 then begin          for j:=1 to Length(IPV4Array) - 1 do begin            i:=Length(Result);SetLength(Result,i+1);            // Copy other properties            Result[i].Index:=Result[i-1].Index;            Result[i].Name:=Result[i-1].Name;            Result[i].MacAddress:=Result[i-1].MacAddress;            Result[i].IPv4:=IPV4Array[j];          end;        end;      end;    end;  end;   {$ENDIF}    // Sort base on index  Comparer:=TNetworkInterfaceComparer.Create;  specialize TArrayHelper.Sort(Result,Comparer);end; {$IFDEF WINDOWS} procedure TNetworkInterfaces.SetWMIQuery(out SWbemLocator: olevariant; out  WMIService: olevariant);const  WbemUser = '';  WbemPassword = '';  WbemComputer = 'localhost';begin  SWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');  WMIService := SWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2',    WbemUser, WbemPassword);end; function OccurrencesOfChar(const S: string; const C: char): integer;var  i: integer;begin  Result := 0;  for i := 1 to Length(S) do begin    if S[i] = C then begin      Inc(Result);    end;  end;end; function TNetworkInterfaces.GetIPV4Address(Index: UInt32): TStringArray;var  SWbemLocator: olevariant;  WMIService: olevariant;  WbemObjectSet: olevariant;  WbemObject: olevariant;  oEnum: IEnumvariant;  iValue: longword;  i,j: integer;begin  Result:=TStringArray.Create;  Self.SetWMIQuery(SWbemLocator,WMIService);   WbemObjectSet := WMIService.ExecQuery(    'SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index= ''' +    IntToStr(Index) + '''', 'WQL', wbemFlagForwardOnly);  oEnum := IUnknown(WbemObjectSet._NewEnum) as IEnumVariant;  //  while oEnum.Next(1, WbemObject, iValue) = 0 do  begin    if not VarIsClear(WbemObject.IPAddress) and not VarIsNull(WbemObject.IPAddress) then begin      for i := VarArrayLowBound(WbemObject.IPAddress, 1)        to VarArrayHighBound(WbemObject.IPAddress, 1)      do begin         // IPV4        if OccurrencesOfChar(WbemObject.IPAddress[i], '.') = 3 then begin          j:=Length(Result);SetLength(Result,j+1);          Result[j]:=WbemObject.IPAddress[i];        end;      end;    end;  end;end; {$ENDIF} {$IFDEF UNIX}function TNetworkInterfaces.GetIPV4Address(IfName: String): String;var  fd: TSocket;  ifr: TIfReq;begin  fd := fpsocket(AF_INET, SOCK_DGRAM, 0);  if fd < 0 then    ExitCode := 1;   ifr.ifr_addr.sin_family := AF_INET;  StrPCopy(ifr.ifr_name, IfName);   if Fpioctl(fd, SIOCGIFADDR, @ifr) < 0 then    ExitCode := 1;   Result:=inet_ntoa(ifr.ifr_addr.sin_addr.s_addr);  CloseSocket(fd);end;{$ENDIF} constructor TNetworkInterfaces.Create;begin  Self.FInterfaces:=Self.GetInterfaces;end; end. ---------------------------------------------------------------------- Jurassic Pork · 2024-08-10 05:55 Hello, you can also use the ipconfig command to have the Mac Address of all the network adapters. Code Example to extract all adapter Names and their Mac Addresses using ipconfig and regular expressions : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i implementationuses regexpr, process;{$R *.lfm}procedure TForm1.Button1Click(Sender: TObject);var s : string;     re: TRegExpr;begin  runcommand('ipconfig',['/all'],s,[],swoHIDE);  try    re := TRegExpr.Create;    re.Expression := 'Description[^:]+:(.*)$\s+' +                     'Adresse physique[^:]+:(.*)$';    re.ModifierM := True;    re.ModifierG := False;    if  re.Exec(s) then    repeat    Memo1.Append(re.Match[1] + ' -> ' + re.Match[2]);    until not re.ExecNext;  finally    re.Free;  end;end;  Replace Description and Adresse physique with your translation. For linux use ip -a  and for macos ifconfig -a. Don't forget to change the pattern of the regex. Friendly, J.P ---------------------------------------------------------------------- the_magik_mushroom · 2024-08-10 22:01 @silvercoder70 I can't get the IPHlpAPI.DLL method to work with lazarus.. the unit network_interfaces works, but I'm not to sure how to get the 'main' mac address, I don't want to list them all. I'll check this. thanks everyone ---------------------------------------------------------------------- ASerge · 2024-08-10 23:56 Quote from: dsiders on August 10, 2024, 12:27:27 amDid you try using GetAdaptersAddresses in the Windows IpHlp API? https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf- iphlpapi-getadaptersaddresses Wrappers in packages/winunit-jedi/src/jwaiphlpapi.pas. Should be faster than spawn a process and parsing the results. +1 And example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses JwaWinError, JwaIpTypes, JwaIpHlpApi; procedure TForm1.Button1Click(Sender: TObject);var  PA, Buffer: PIpAdapterAddresses;  BufLen: LongWord;  Result: LongWord;  B: Byte;  MAC: string;begin  BufLen := 0;  Result := GetAdaptersAddresses(0, 0, nil, nil, @BufLen);  if Result <> ERROR_BUFFER_OVERFLOW then    RaiseLastOSError(Result);  GetMem(Buffer, BufLen);  try    Result := GetAdaptersAddresses(0, 0, nil, Buffer, @BufLen);    if Result <> ERROR_SUCCESS then      RaiseLastOSError(Result);    PA := Buffer;    repeat      if PA^.PhysicalAddressLength = 0 then        MAC := 'do not have a data-link layer'      else      begin        MAC := '';      for B in PA^.PhysicalAddress do        begin          if MAC <> '' then            MAC := MAC + ':';          MAC := MAC + IntToHex(B);      end;      end;      Memo1.Append(Format('%s'#9'%s, %s', [MAC, PA^.Description, PA^.FriendlyName]));      PA := PA^.Next;    until PA = nil;  finally    FreeMem(Buffer);  end;end; ---------------------------------------------------------------------- bpranoto · 2024-08-11 00:14 Quote from: the_magik_mushroom on August 11, 2024, 12:01:00 am... the unit network_interfaces works, but I'm not to sure how to get the 'main' mac address, I don't want to list them all. I'll check this. thanks everyone  I think there's no main mac address. In my code I sort the list by  the interface index. As long as I test, the order is the same with the windows ipconfig or linux ifconfig output command. Please check ---------------------------------------------------------------------- Thaddy · 2024-08-11 08:04 Indeed, there is no such thing as a "main" MAC address. ---------------------------------------------------------------------- Thaddy · 2024-08-11 12:12 Quote from: silvercoder70 on August 10, 2024, 04:00:06 amThis code should (?) work and uses IPHlpAPI DLL... (I know it works in Delphi )Yes, that code works in FPC too, but you need to use jwaWindows instead of windows, iphlpapi and its type unit. IOW uses jwaWindows, sysutils; Or simply jwaIpHlpApi. ( but I am lazy, so if I am missing a windows unit I tend to simply use jwaWindows, which includes almost all Windows api's in one go. There is regularly missing a few bits and bolts, though) ---------------------------------------------------------------------- the_magik_mushroom · 2024-08-13 00:52 Yes thank you the uses JwaWinError, JwaIpTypes, JwaIpHlpApi; was missing. when I wrote the 'main' mac address, I mean the first one you get when you type the cmd getmac. here is the list I get with your code ASerge: do not have a data-link layer 00:FF:AE:0C:E2:2F:00:00 do not have a data-link layer 8C:55:4A:AF:11:33:00:00 8E:55:4A:AF:11:32:00:00   << that's the one I want from my getmac code 8C:55:4A:AF:11:32:00:00 8C:55:4A:AF:11:36:00:00 do not have a data-link layer ---------------------------------------------------------------------- ASerge · 2024-08-14 15:27 Quote from: the_magik_mushroom on August 13, 2024, 02:52:52 amdo not have a data-link layer 00:FF:AE:0C:E2:2F:00:00 do not have a data-link layer 8C:55:4A:AF:11:33:00:00 8E:55:4A:AF:11:32:00:00   << that's the one I want from my getmac code 8C:55:4A:AF:11:32:00:00 8C:55:4A:AF:11:36:00:00 do not have a data-link layer You can perform filtering over an Ethernet network. Add jwaIpIfCons in uses, and Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i ...if PA^.IfType = IF_TYPE_ETHERNET_CSMACD then  Memo1.Append(... ---------------------------------------------------------------------- Jurassic Pork · 2024-08-14 17:35 Hello, Quote from: the_magik_mushroom on August 09, 2024, 11:04:41 pmsimple question but how to simply and quickly get the mac address in win7/10/11? the only way I managed with chatgpt is kind of dirty (an invisible cmd line with getmac and scrapping the result): It's slow (~0.4 sec on my system) anyway to get it faster?  IpConfig in a runcommand with swoHide mode is faster :  60 ms with  regex extract and display : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i implementation uses regexpr, process;{$R *.lfm}procedure TForm1.Button1Click(Sender: TObject);var s : string;     re: TRegExpr;    ET : TEpikTimer;begin  ET := TEpikTimer.Create(Nil);  ET.Clear;  ET.Start;  runcommand('ipconfig',['/all'],s,[],swoHIDE);  try    re := TRegExpr.Create;    re.Expression := 'Description[^:]+:(.*)$\s+' +                     'Adresse physique[^:]+:(.*)$';    re.ModifierM := True;    re.ModifierG := False;    if  re.Exec(s) then    repeat      Memo1.Append(re.Match[1] + ' -> ' + re.Match[2]);    until not re.ExecNext;  finally    re.Free;    Memo1.Append('Elapsed Time : ' + FloatToStr(ET.ELapsed) );  end;end;   Friendly, J.P