This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathugetipadress.pas
83 lines (75 loc) · 1.74 KB
/
ugetipadress.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
unit UGetIPAdress;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Process;
type
TGetIPAdress = class
public
function getIP: string;
private
{$IFDEF WINDOWS}
function GetIpAddrList: string;
{$ENDIF}
end;
implementation
function TGetIPAdress.getIP: string;
var
response: TStringList;
{$IFDEF LINUX}
process: TProcess;
{$ENDIF}
begin
{$IFDEF WINDOWS}
response:=TStringList.create;
response.delimiter:=' ';
response.delimitedText:=GetIpAddrList;
result:=response[1];
{$ENDIF}
{$IFDEF LINUX}
process:=TProcess.create(nil);
process.executable:='sh';
process.parameters.add('-c');
process.parameters.add('hostname -I | awk ''{print $1}''');
process.options:=process.options + [poWaitOnExit, poUsePipes];
process.showWindow:=swoHIDE;
process.execute;
response:=TStringList.create;
response.LoadFromStream(process.output);
process.free;
result:=trim(response[0]);
response.free;
{$ENDIF}
end;
{$IFDEF WINDOWS}
function TGetIPAdress.GetIpAddrList: string;
var
AProcess: TProcess;
s: string;
sl: TStringList;
i, n: integer;
begin
Result:='';
sl:=TStringList.Create();
AProcess:=TProcess.Create(nil);
AProcess.CommandLine := 'ipconfig.exe';
AProcess.Options := AProcess.Options + [poUsePipes, poNoConsole];
try
AProcess.Execute();
Sleep(500); // poWaitOnExit don't work as expected
sl.LoadFromStream(AProcess.Output);
finally
AProcess.Free();
end;
for i:=0 to sl.Count-1 do
begin
if (Pos('IPv4', sl[i])=0) and (Pos('IP-', sl[i])=0) and (Pos('IP Address', sl[i])=0) then Continue;
s:=sl[i];
s:=Trim(Copy(s, Pos(':', s)+1, 999));
if Pos(':', s)>0 then Continue; // IPv6
Result:=Result+s+' ';
end;
sl.Free();
end;
{$ENDIF}
end.