
04.07.2025, 13:17
|
Новичок
|
|
Регистрация: 18.03.2009
Сообщения: 81
Репутация: 10
|
|
Как по PID вывести соединение программы
Здравствуйте! как зная PID вывести все соединение программы?
Код:
function RunCommandAndCaptureOutput(const CmdLine: string; OutputLines: TStrings): Boolean;
var
Security: TSecurityAttributes;
ReadPipe, WritePipe: THandle;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
Buffer: array[0..255] of Byte;
BytesRead: DWORD;
S: string;
begin
Result := False;
Security.nLength := SizeOf(TSecurityAttributes);
Security.bInheritHandle := True;
Security.lpSecurityDescriptor := nil;
if not CreatePipe(ReadPipe, WritePipe, @Security, 0) then Exit;
try
ZeroMemory(@StartupInfo, SizeOf(StartupInfo));
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.hStdOutput := WritePipe;
StartupInfo.hStdError := WritePipe;
StartupInfo.dwFlags := STARTF_USESTDHANDLES;
if not CreateProcess(nil, PChar(CmdLine), nil, nil, True,
CREATE_NO_WINDOW, nil, nil, StartupInfo, ProcessInfo) then
Exit;
CloseHandle(WritePipe);
S := '';
repeat
BytesRead := 0;
ZeroMemory(@Buffer, SizeOf(Buffer));
if ReadFile(ReadPipe, Buffer, SizeOf(Buffer), BytesRead, nil) then
begin
if BytesRead > 0 then
begin
S := S + String(PAnsiChar(@Buffer[0]));
end;
end;
until BytesRead = 0;
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
// Разделяем строки
OutputLines.Text := S;
Result := True;
finally
CloseHandle(ReadPipe);
end;
end;
Код:
procedure GetIPsByPID(PID: DWORD; Memo: TMemo);
var
OutputLines: TStringList;
Line: string;
SearchStr: string;
P: Integer;
begin
Memo.Clear;
// Запускаем netstat
OutputLines := TStringList.Create;
try
if not RunCommandAndCaptureOutput('netstat -ano', OutputLines) then
begin
Memo.Lines.Add('Ошибка запуска netstat');
Exit;
end;
// Ищем строки с нужным PID
for Line in OutputLines do
begin
SearchStr := ' ' + IntToStr(PID) + ' ';
if Pos(SearchStr, Line) > 0 then
begin
// В строке ищем IP-адреса
// Обычно строки вида: TCP 192.168.1.2:12345 93.184.216.34:80 ESTABLISHED
// Разделяем по пробелам
// Можно парсить вручную или искать IP-адреса
Memo.Lines.Add(Line);
end;
end;
finally
OutputLines.Free;
end;
end;
Код:
GetIPsByPID(12156, Memo1);
у меня ошибка KERNELLBASE 
|