// This Delphi function performs direct ping, or proxy ping.
// When doing a direct ping, the local computer pings the remote computer directly.
// Direct ping works only if the local computer is Windows XP or higher.
// When doing proxy ping, the local computer delegates to the proxy computer,
// which performs the ping. The local computer then gets the results from proxy.
// Proxy ping works only if the proxy computer is Windows XP or higher.
// For direct ping ProxyHost, ProxyUserName, ProxyPassword parameters must be empty.
// For proxy ping the parameters are:
// ProxyHost: the IP address or name of proxy computer, like '10.8.36.54';
// ProxyUserName: name of the user, to use when connecting to proxy computer,
// may include domain, like 'MOON\Administrator';
// ProxyPassword: the user's password for proxy computer;
// Destination: IP address, or name of the computer to ping.
// The function returns PING status, zero meaning success, otherwise error.
function DoPing(ProxyHost, ProxyUserName, ProxyPassword, Destination: string): integer;
var
vQuery: TWmiQuery;
vConnection: TWmiConnection;
begin
Result := -1;
vQuery := TWmiQuery.Create(nil);
vConnection := TWmiConnection.Create(nil);
try
vConnection.MachineName := ProxyHost;
vConnection.Credentials.UserName := ProxyUserName;
vConnection.Credentials.Password := ProxyPassword;
// This block may fail if
// - WMI is not install (like windows 95, 98, NT without WMI core installed);
// - provided credentials are not valid
// - local computer is not WinXP or higher (direct ping)
// - proxy computer is not WinXP or higher (proxy ping)
try
vConnection.Connected := true;
vQuery.WQL.Text := 'select * from Win32_PingStatus where '+
'Address = ''' + Destination + ''' and Timeout = 4000';
vQuery.Connection := vConnection;
vQuery.Open;
// check the status. Also use ResponseTime field to know roundtrip time
if not vQuery.EOF then Result := vQuery.FieldByName('StatusCode').AsInteger;
except
Exit;
end;
finally
vQuery.Free;
vConnection.Free;
end;
end;
|