[fpc-pascal] cannot read /sys/class/net/eth1/address even as root user on linux

Dennis Poon dennis at avidsoft.com.hk
Fri Jan 3 08:26:25 CET 2014



Michael Van Canneyt wrote:
>
>
> On Thu, 5 Dec 2013, Dennis Poon wrote:
>
>> I tried to read the mac address in the captioned file path.
>> In terminal, I can simply 'cat' and display the mac address.
>>
>> In FPC, when I tried to use TFileStream to read it,
>>
>>  FS := TFileStream.Create('/sys/class/net/eth1/address', 
>> fmOpenRead+fmShareDenyWrite);
>>
>> it raised "stream read error"
>
> home: >./t
> 00:1f:d0:a2:df:c4
>
> home: >cat t.pp
> {$mode objfpc}
> {$H+}
> uses sysutils, classes;
>
> Var
>   S : String;
>
> begin
>   SetLength(S,100);
>   with TFileStream.Create('/sys/class/net/eth1/address', 
> fmOpenRead+fmShareDenyWrite) do
>     try
>       SetLength(S,Read(S[1],100));
>       Writeln(S);
>     finally
>       free;
>     end;
> end.
>
>
> Works fine here. Permission problem on your machine maybe ?
>
> Michael.
>

So, strange.
I tried again and found that it works if I uses BaseUnix and then call 
fpRead but not with TFileStream.Read

My interface uses are:

uses
   Classes, SysUtils, DB, iniFiles;

My implementation uses:
uses md5, uStrUtils
   {$IFDEF UNIX}
      ,BaseUnix
   {$ENDIF}

   ;


function GetUnixMac(TheDevice : String) : String;
const
   UnixPath = '/sys/class/net/%s/address';
   var s,
       FileName : String;
       FS : TFilestream;

     Var fHandle : cint;
         len : longint;
         buffer :string[255];
   begin
     result := '';
     FileName := Format(UnixPath,[TheDevice]);
     if FileExists(FileName) then begin
//this fpread will work and give me mac address
         fHandle:=fpOpen(FileName,O_RdOnly);
         If fHandle > 0 then
           try
             len := fpRead (fHandle,buffer[1],255);
             setlength(Buffer,len);

             Log(TheDevice+' Mac:'+buffer);
             result := StringReplace(buffer,#10,';',[rfReplaceAll]);
           finally
             fpClose(fHandle);
           end;

{//strange, the following will raise stream read error
         FS := TFilestream.Create(FileName, fmOpenRead+fmShareDenyWrite );
         try
           if FS.Size > 0 then begin
             SetLength(s, FS.Size);
             FS.ReadBuffer(s[1], FS.Size);
             Log(TheDevice+' Mac:'+S);
             result := StringReplace(s,#10,';',[rfReplaceAll]);
           end;
         finally
           FreeAndNil(FS);
         end;
}
     end;
   end;

Why your machine works but my does not and has to rely on fpRead instead 
of TFileStream???

Dennis






More information about the fpc-pascal mailing list