Linux下代码不熟,还不如shell,主要注意要加bash -c,否则只能执行ifconfig,后面的|grep等等不会被执行
另外这个双引号估计有坑,等后面遇到再说
program project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, process
{ you can add units after this };
function GetLocalIP1: string;
var
AProcess: TProcess;
sl: TStringList;
begin
Result:='';
sl := tstringlist.create;
AProcess:=TProcess.Create(nil);
AProcess.CommandLine := 'bash -c "/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk ''{print $2}''|tr -d "addr:""';
AProcess.Options := AProcess.Options + [poUsePipes, poWaitOnExit];
try
AProcess.Execute();
sl.LoadFromStream(AProcess.Output);
finally
AProcess.Free();
end;
Result := sl.Text;
sl.Free();
end;
function GetLocalIP2:string;
var
s: string;
begin
if RunCommand('bash -c "/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk ''{print $2}''|tr -d "addr:""',s) then result :=s else result :='';
end;
begin
writeln(GetLocalIP1);
writeln(GetLocalIP2);
end.
网友评论