You are on page 1of 12

17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

PROJECTS MISC CATEGORIES ABOUT CONTRIBUTIONS

THE ROAD TO DELPHI Delphi – Free Pascal – Oxygene

Making a PING with Delphi and the WMI


February 2, 2011 by Rodrigo | 36 Comments

Typically we use the IcmpSendEcho function or a component like


TIdIcmpClient to make a ping request from Delphi. Today I will show
you another way to do this using the WMI (Windows Management
Instrumentation).

The WMI class which allow you to make a ping request is


Win32_PingStatus, to use this class you only need to pass the
parameter Address value in your WQL sentence , the form of the Embarcadero MVP
Address parameter can be either the computer name (ACCOUNT-PC),
IPv4 address (192.168.154.102), or IPv6 address
(2010:836B:4179::836B:4179).
.Net Applications Bing
API COM
1 SELECT * FROM Win32_PingStatus where Address='www.goo
Delphi Delphi-
News Delphi 2010
Some of the advantages of use this class to make a ping is which Delphi Prism Delphi XE
supports IPv4 addresses and IPv6 addresses (Starting with Windows Delphi XE2 Delphi XE3
Delphi XE4 DWM
Vista) , and you can set the ping parameters in a single WQL sentence. FreePascal Geolocation
Github Google Api
Lazarus Networking
For example if you want send a Buffer of 64 bytes (instead of the 32 OSX Oxygene RTTI
default size) and resolve the address of the host server you only need SMBios Tools
to write a sentence like this : TWebBrowser VCL
Styles WinApi WMI
XML XPath
1 SELECT * FROM Win32_PingStatus where Address='192.168

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 1/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

BLOG STATS
Now check this sample console application.
1,871,417 hits

1 program WMIPing;
2
3 {$APPTYPE CONSOLE} SEARCH
4
5 uses
6 SysUtils,
7 ActiveX, SEARCH
8 ComObj,
9 Variants;
10
11 function GetStatusCodeStr(statusCode:integer) : str
12 begin
FOLLOW B LOG VIA
13 case statusCode of EMAIL
14 0 : Result:='Success';
15 11001 : Result:='Buffer Too Small'; Enter your email address
16 11002 : Result:='Destination Net Unreachable'; to follow this blog and
17 11003 : Result:='Destination Host Unreachable'; receive notifications of
18 11004 : Result:='Destination Protocol Unreachab new posts by email.
19 11005 : Result:='Destination Port Unreachable'; Join 1,331 other followers
20 11006 : Result:='No Resources'; Enter your email address
21 11007 : Result:='Bad Option';
Follow
22 11008 : Result:='Hardware Error';
23 11009 : Result:='Packet Too Big';
24 11010 : Result:='Request Timed Out';
25 11011 : Result:='Bad Request';
26 11012 : Result:='Bad Route'; FOLLOW M E ON
27 11013 : Result:='TimeToLive Expired Transit'; TWIT TER
28 11014 : Result:='TimeToLive Expired Reassembly'
29 11015 : Result:='Parameter Problem'; My Tweets
30 11016 : Result:='Source Quench';
31 11017 : Result:='Option Too Big';
32 11018 : Result:='Bad Destination';
33 11032 : Result:='Negotiating IPSEC';
34 11050 : Result:='General Failure'
35 else
36 result:='Unknow';
37 end;
38 end;
39
40
41 //The form of the Address parameter can be either t TRANSLATE
42 procedure Ping(const Address:string;Retries,Buffer
43 var Translate this blog into
44 FSWbemLocator : OLEVariant; different languages...
45 FWMIService : OLEVariant;
46 FWbemObjectSet: OLEVariant;
47 FWbemObject : OLEVariant; ‫اﻟﻌرﺑﯾﺔ‬
48 oEnum : IEnumvariant; Български
49 iValue : LongWord; 中文(简体)
50 i : Integer; 中文(繁體)
51
52 PacketsReceived : Integer; Hrvatski
53 Minimum : Integer; Česky
54 Maximum : Integer; Dansk
55 Average : Integer; Nederlands
56 begin;
57 PacketsReceived:=0; Suomi
58 Minimum :=0; Français
59 Maximum :=0; Deutsch
60 Average :=0; Ελληνική
https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 2/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

61 Writeln(''); िह ी
62 Writeln(Format('Pinging %s with %d bytes of data: Italiano
63 FSWbemLocator := CreateOleObject('WbemScripting.S
日本語
64 FWMIService := FSWbemLocator.ConnectServer('loc
65 //FWMIService := FSWbemLocator.ConnectServer('1 한국어
66 for i := 0 to Retries-1 do Norsk
67 begin Polski
68 FWbemObjectSet:= FWMIService.ExecQuery(Format('
Português
69 oEnum := IUnknown(FWbemObjectSet._NewEn
70 if oEnum.Next(1, FWbemObject, iValue) = 0 then Română
71 begin Русский
72 if FWbemObject.StatusCode=0 then Español
73 begin
Svenska
74 if FWbemObject.ResponseTime>0 then
75 Writeln(Format('Reply from %s: bytes=%s t
76 else
77 Writeln(Format('Reply from %s: bytes=%s t
78
79 Inc(PacketsReceived);
80
81 if FWbemObject.ResponseTime>Maximum then
82 Maximum:=FWbemObject.ResponseTime;
83
84 if Minimum=0 then
85 Minimum:=Maximum;
86 BLOGROLL
87 if FWbemObject.ResponseTime<Minimum then
88 Minimum:=FWbemObject.ResponseTime; Andy’s Blog and Tools
89
Delphi – Neftali
90 Average:=Average+FWbemObject.ResponseTime;
91 end Delphi Haven – Chris
92 else Rolliston Blog
93 if not VarIsNull(FWbemObject.StatusCode) then
94 Writeln(Format('Reply from %s: %s',[FWbemOb Delphi sorcery – Stefan
95 else Glienke's Blog
96 Writeln(Format('Reply from %s: %s',[Address Delphifeeds.com
97 end;
98 FWbemObject:=Unassigned; Felix J COLIBRI
99 FWbemObjectSet:=Unassigned; Hallvard's Blog
100 //Sleep(500);
101 end; Hey, Scripting Guy! Blog
102 JEDI Windows API
103 Writeln('');
104 Writeln(Format('Ping statistics for %s:',[Address Peter Johnson's
105 Writeln(Format(' Packets: Sent = %d, Received DelphiDabbler.com
106 if PacketsReceived>0 then Reinvent The Wheel
107 begin
108 Writeln('Approximate round trip times in milli-s RemObject Blog
109 Writeln(Format(' Minimum = %dms, Maximum = %d Rudy's Delphi Corner
110 end;
111 end; Scott Hanselman Blog
112 Sip from the Firehose
113
114 begin The Art of Delphi
115 try Programming
116 CoInitialize(nil); The Delphi Geek
117 try
118 //Ping('192.168.52.130',4,32); The Old New Thing
119 Ping('theroadtodelphi.wordpress.com',4,32); The Oracle at Delphi
120 finally
121 CoUninitialize; The TIndex
122 end; YAPB – Alex Ciobanu Blog
123 except
124 on E:Exception do
125 Writeln(E.Classname, ':', E.Message);
https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 3/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

126 end; REC ENT P OSTS


127 Readln;
128 end. VCL Styles Utils – New
version released
VCL Styles Utils –
And the output New version
New VCL Styles from
DelphiStyles.com
DITE and DIC now
supports RAD Studio
10.2 Tokyo
TSMBIOS now supports
Linux via Delphi
10.2 Tokyo.

CATEGOR IES

.Net (13)
ADO (2)
ADSI (1)
Applications (16)
Bing API (3)
C# (2)
C++ Builder (1)

Share this: COM (9)

     
Cpp (1)
Email Print Facebook Reddit Pocket Twitter
Delphi (207)

 LinkedIn   Tumblr Pinterest Delphi 2010 (7)


Delphi Prism (12)

Like Delphi XE (7)

Be the first to like this. Delphi XE2 (27)


Delphi XE3 (15)
Delphi XE4 (3)
Related
Delphi XE5 (1)
Accesing the WMI WMI Tasks using Accesing the WMI Delphi-News (10)
from Delphi and Free Delphi – Networking from Object Pascal DWM (3)
Pascal via COM In "Delphi" Code (Delphi,
Firebird (1)
(without late binding Oxygene, FreePascal)
or In "Delphi" FireMonkey (2)

WbemScripting_TLB) FreePascal (8)


In "COM" Geolocation (3)
Github (3)
Google Api (9)
Google labs (2)
Categories: Delphi, Networking, WMI | Tags: Delphi, Networking, WMI | Permalink.
InnoSetup (2)
iOS (1)
Javascript (1)
https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 4/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

JEDI API (2)


Author: Rodrigo
json (2)
Just another Delphi guy.
Lazarus (6)
Linux (1)
Networking (14)
OSX (3)
Oxygene (4)
PreviewHandler (2)
Rest (1)
RTTI (5)
36 THOUGHTS ON “MAKING A PING WITH RTTI (1)
DELPHI AND THE WMI” SMBios (6)
SQL CLR (1)
Leave a comment
Sql Server (1)
StackOverflow (1)
Pingback: Making a PING with Delphi and the WMI Tools (22)
TWebBrowser (3)
VCL Styles (39)
Wanc
WinApi (16)
February 2, 2011 at 8:48 am
WinInet (1)
Nice post, but the code has broken lines.
WMI (37)
Please don’t use tags, use tags, like this :
WUA (1)
XML (3)
1 if FWbemObject.ResponseTime>Maximum then
2 Maximum:=FWbemObject.ResponseTime; XPath (3)

Thanks.
DELPHIFEEDS
Thanks.
An error has occurred; the
Reply feed is probably down. Try
again later.

Rodrigo
February 2, 2011 at 2:37 pm
STACKOVERFLOW
WanC , which browser are you using? the code looks good DELPHI QUESTION S
in Firefox and IE Explorer.
Delphi : How to use
Reply system.RegularExpressions
in my case? October 17,
2019 rooky06
How to avoid that
Radu
TStrings.SaveToFile creates
February 2, 2011 at 9:07 am
a final empty line? October
17, 2019 Fabrizio
Hi Rodrigo,
Real-Time Collaboration
As usual exceptional examples with very useful information! [on hold] October 16, 2019
On this example I could suggest you to change Soufiane Bra

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 5/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

“FWMIService := FSWbemLocator.ConnectServer(‘localhost’, Transparent bitmaps as


‘root\CIMV2’, ”, ”);” with resources? October 16,
2019 Marus Nebunu
” FWMIService := FSWbemLocator.ConnectServer(”, ”, ”, ”);”
Standard method for
due to fact that SWbemLocator.ConnectServer method takes by
creating dll in c++ and
default the system parameters, if you don’t want to put them calling in delphi October
explicit. And you have several comments there, even an IP 16, 2019 Hamed
adress :) Inside DataSnap Server
Method, How to read all
Please keep up the good work, it’s always interesting to read
request header October
your blog! 16, 2019 Roberto
Novakosky
Best regards,
Adding parent to child
Radu
document October 16,
Reply 2019 MedHome
Jasper very slow to
generate with .jar (20
seconds) October 16, 2019
Rodrigo
Gwenael
February 2, 2011 at 2:41 pm
Delphi using DLL Pointer
Radu, thanks for your comments, about your suggestion Parameter October 16,
is always recommendable pass the namespace and the 2019 Larry

machine name when you use the ConnectServer function. How to Parse JSON in
about the commented line is just for illustrate which you Delphi [duplicate] October
16, 2019 Ant
can make a ping from a remote machine using the WMI.

Reply

Domingo
February 2, 2011 at 10:03 am

Muy bueno el código !!!

Gracias

Reply

Rodrigo
February 2, 2011 at 2:41 pm

Domingo, gracias por tus comentarios.


TOP POSTS & PAGE S
Reply
VCL Styles - Adding
background images and
colors to Delphi forms
Rafael Colucci Using the Google Maps API
April 5, 2011 at 10:53 am V3 from Delphi - Part I
Basic functionality
Hello
Manipulating local/remote
There is a problem with your code. If you try to ping a invalid files and folders using
address like ‘aaaa’ you get this error message: Delphi and WMI
Is Your Delphi IDE Hot or
Project WMIPing.exe raised exception class Not? - Introducing the
EVariantTypeCastError with message ‘Could not convert variant Delphi IDE Theme Editor
https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 6/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

of type (Null) into type (Integer). Changing the color of Edit


Controls with VCL Styles
To reproduce this error, simple change: Enabled
Ping(‘theroadtodelphi.wordpress.com’,4,32); Accesing the WMI from
Object Pascal Code
for (Delphi, Oxygene,
FreePascal)
Ping(‘aaaaaa’,4,32);
Generating a "unique"
in this case, FWbemObject.StatusCode is getting NULL instead hardware ID using Delphi
of the error code. and the WMI
Compile, Debug and Run
Reply your Pascal code online.
Generating Qr Codes with
Delphi
Rodrigo Change the drive letter
April 5, 2011 at 11:17 am
using WMI and Delphi

Rafael the problem is due (as you say) which the


StatusCode property return a null value which cannot be
translated to a valid status message, the code was
modified to handle this issue. try now and let me know
the results of your tests.

Reply

Rafael Colucci
April 5, 2011 at 12:39 pm

OK .. the problem is gone now (i had already did


what you just did). But it seems to me that the
Status code is always null when an address is
invalid. This way, you will never get the error status
when you use GetStatusCodeStr. Every invalid
address i have tried gets a null status code.

Reply

Rodrigo
April 5, 2011 at 12:56 pm

Rafael. try checking the value of the


PrimaryAddressResolutionStatus property this
value always return a valid code (not null) even
if the address passed is invalid, you can
translate the value to an string using the
GetStatusCodeStr function.

Reply

Rafael Colucci
April 5, 2011 at 1:10 pm

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 7/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

OK. Now it works perfect. You should


consider changing your source code also.
Thanks for you help and good job btw.

Rodrigo
April 5, 2011 at 1:15 pm

ok, no problem, glad to help you.

EMB
August 29, 2011 at 3:01 pm

Just had to use this today. (:


Gold as always.
Do you know any drawback of using this comparing to usual
IcmpSendEcho approach?
thanks!

EMB

Reply

Rodrigo
August 29, 2011 at 3:48 pm

There is not drawbacks, you can get the same results


using the IcmpSendEcho function or the
Win32_PingStatus wmi class.

Reply

EMB
August 30, 2011 at 10:40 am

Thanks! (:
the problem with IcmpSendEcho is that we should
not statically link to the library. Instead, call
LoadLibrary and then GetProccess, and if fails, try
again.
Sometimes, I just wanna a simpler code that work in
all target windows…

Reply

Pingback: WMI Tasks using Delphi – Networking « The Road to Delphi – a Blog
about programming

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 8/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

Abraão
August 9, 2012 at 8:31 am

Hi Rodrigo, i would like of handle the timeout of the ping


request . Could you give me some tips in how implement it
using your source code?

Reply

Rodrigo
February 7, 2013 at 12:22 am

Just use the TimeOut property like so

1 SELECT * FROM Win32_PingStatus where Addre

P.D : Sorry for the late response.

Reply

Massimo Voto
June 23, 2013 at 2:50 am

Hi Rodrigo
Thank for good example. The ICMP of Indy on W7 64 not work,
and your example work for all target windows.

Reply

víctor
November 7, 2013 at 3:46 pm

Muchas gracias por este trabajo!

Reply

asqar
February 3, 2014 at 12:11 pm

Hi. thank you from your good example.


I have a question. How to change the port that is uses to ping
via this method?
Thank you very much.

Reply

Rodrigo
February 3, 2014 at 12:25 pm

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 9/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

The Win32_PingStatus WMI Class uses the ICMP protocol


to make a echo request, and ICMP does not use ports, so
you cannot set a port in a ping request.

Reply

asqar
February 3, 2014 at 1:08 pm

Thank you from your answer

Reply

Jorge Abel
April 30, 2014 at 11:13 am

Como usaria este codigo en una aplicacion Win32 usando


Delphi XE ???

Reply

Rodrigo
April 30, 2014 at 4:09 pm

Hola Jorge, el codigo de ejemplo es de una aplicacion de


consola, si deseas usarla en una aplicaicon VCL solo
debes adaptar el codigo reemplazando las llamadas al
procedimiento Writeln.

Reply

Olav
September 30, 2014 at 2:28 pm

This code is really nice. However if the pinged computer is


offline it takes ages to get a response. Can this be made
quicker? Any suggestions?

Reply

Rodrigo
October 2, 2014 at 10:40 am

Try using the Timeout property if the Win32_PingStatus


class.

Reply

Sean Roulo
November 1, 2014 at 7:43 pm

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 10/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

Beautiful solution… pulled my hair out on making


IcmpSendEcho work… basically would return 0 even when I
could ping the host via command line. This worked flawlessly…
thank you so much Rodrigo… you are a rock star my friend!

Reply

Rob
January 28, 2015 at 3:55 am

Great!really appreciate this, was struggling with the


IcmpSendEcho.

Reply

dagobert
March 20, 2016 at 10:36 am

Hello rodrigo, many thanks for this example.


I use the response time for calculations. With fast local
conections the time is 1ms. Also i used more ping bytes. Do
you know a easy :-) way to show the response time for example
in micro seconds?
Many many thanks

Reply

Rodrigo
March 20, 2016 at 11:23 pm

The ping accuracy of the Win32_PingStatus class is


milliseconds. I’m not aware of another class or function
which provides a better accuracy.

Reply

Arthur Guimarães
June 22, 2016 at 10:36 am

Hi there I tried to use ICMP to ping a device on windows server


2012 and it takes 3 seconds to process Client.Ping; when client
is offline. When its done on a windows server 2003 client.Ping;
takes less than a second to inform the client is offline.
Do you know how long does it takes to process a ping through
your code WMI if client is offline?
Thanks

Reply

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 11/12
17/10/2019 Making a PING with Delphi and the WMI | The Road to Delphi

Rodrigo
June 22, 2016 at 5:09 pm

NO, I don’t made that test before, but you can try
yourself.

Reply

Volker Giese
October 24, 2016 at 10:59 am

Hi Rodrigo,

your code is the perfect option for my automatic backup


system, after I had trouble working with the ICMP approach.
Thank you

Reply

Rodrigo
October 24, 2016 at 11:07 am

You are welcome.

Reply

Leave a Reply
Enter your comment here...

← Previous Post Next Post →

Blog at WordPress.com.
Top

https://theroadtodelphi.com/2011/02/02/making-a-ping-with-delphi-and-the-wmi/ 12/12

You might also like