gpt4 book ai didi

delphi - 如何在不使用 Indy 组件的情况下在 Delphi 10.1 中 ping IP 地址?

转载 作者:行者123 更新时间:2023-12-03 15:23:09 27 4
gpt4 key购买 nike

如何在不使用 Indy 组件的情况下在 Delphi 10.1 中 ping IP 地址(或通过服务器名称)? TIdICMPClient 使用提升的权限工作,但我想以普通用户身份执行此操作。

最佳答案

其他答案缺少一些内容。

这是一个可以实现这一目的的完整单元:

unit Ping2;

interface

function PingHost(const HostName: AnsiString; TimeoutMS: cardinal = 500): boolean;

implementation

uses Windows, SysUtils, WinSock;

function IcmpCreateFile: THandle; stdcall; external 'iphlpapi.dll';
function IcmpCloseHandle(icmpHandle: THandle): boolean; stdcall;
external 'iphlpapi.dll';
function IcmpSendEcho(icmpHandle: THandle; DestinationAddress: In_Addr;
RequestData: Pointer; RequestSize: Smallint; RequestOptions: Pointer;
ReplyBuffer: Pointer; ReplySize: DWORD; Timeout: DWORD): DWORD; stdcall;
external 'iphlpapi.dll';

type
TEchoReply = packed record
Addr: In_Addr;
Status: DWORD;
RoundTripTime: DWORD;
end;

PEchoReply = ^TEchoReply;

var
WSAData: TWSAData;

procedure Startup;
begin
if WSAStartup($0101, WSAData) <> 0 then
raise Exception.Create('WSAStartup');
end;

procedure Cleanup;
begin
if WSACleanup <> 0 then
raise Exception.Create('WSACleanup');
end;

function PingHost(const HostName: AnsiString;
TimeoutMS: cardinal = 500): boolean;
const
rSize = $400;
var
e: PHostEnt;
a: PInAddr;
h: THandle;
d: string;
r: array [0 .. rSize - 1] of byte;
i: cardinal;
begin
Startup;
e := gethostbyname(PAnsiChar(HostName));
if e = nil then
RaiseLastOSError;
if e.h_addrtype = AF_INET then
Pointer(a) := e.h_addr^
else
raise Exception.Create('Name doesn''t resolve to an IPv4 address');

d := FormatDateTime('yyyymmddhhnnsszzz', Now);

h := IcmpCreateFile;
if h = INVALID_HANDLE_VALUE then
RaiseLastOSError;
try
i := IcmpSendEcho(h, a^, PChar(d), Length(d), nil, @r[0], rSize, TimeoutMS);
Result := (i <> 0) and (PEchoReply(@r[0]).Status = 0);
finally
IcmpCloseHandle(h);
end;
Cleanup;
end;

end.

您可以使用如下点击事件来调用它:

procedure TForm1.button1Click(Sender: TObject);
begin
if PingHost('172.16.24.2') then
ShowMessage('WORKED')
else
ShowMessage('FAILED');
end;

请记住将“Ping2”单位添加到您的用途列表中。

关于delphi - 如何在不使用 Indy 组件的情况下在 Delphi 10.1 中 ping IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com