美文网首页
Lazarus调用shell获取本机IP

Lazarus调用shell获取本机IP

作者: 前尘旧歌 | 来源:发表于2020-05-14 02:12 被阅读0次

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.

相关文章

网友评论

      本文标题:Lazarus调用shell获取本机IP

      本文链接:https://www.haomeiwen.com/subject/aktznhtx.html