The advanced ping

image_pdfimage_print

Sometimes you ping a computer, but due to old local DNS cache, the ‘wrong’ computer replies, even after a ipconfig /flushdns. In this script it is solved by pinging the IP address and resolve it back to its hostname.

A little bit more about the solution:

  • You ping a hostname with – for example:
    ping computername
    
  • You receive a IP address back, for example 192.168.4.5.
  • With the command:
    ping -a 192.168.4.5
    

    You receive a hostname back.

  • You check the returned hostname with the requested hostname and if they match, it is ok. And if they do not match, then the hostname cannot be reached.

The code:

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
Option Explicit
 
dim strComputers : strComputers = "dc01,dc02,comp1,comp2"
dim arrComputers : arrComputers = split(strComputers,",")
dim objComputer
 
For Each objComputer in ArrComputers
    wscript.echo "Testing: " & objComputer & ". Result: " & Reachable(objComputer)
Next
 
Function Reachable(strHostName)
 
  Const ForReading      = 1
  Const TemporaryFolder = 2
 
  Dim fn_objWMIService
  Dim fn_colPings
  Dim fn_objStatus
  Dim fn_objShell
  Dim fn_objFSO
  Dim strTempFile
  Dim results
  Dim ts
  Dim retString
 
  strHostName = lcase(strHostName)
 
 
  Set fn_objWMIService     = GetObject("winmgmts:\\.\root\cimv2")
  Set fn_colPings          = fn_objWMIService.ExecQuery ("Select * From Win32_PingStatus where Address = '" & strHostName & "'")
 
  For Each fn_objStatus in fn_colPings
    If IsNull(fn_objStatus.StatusCode) or fn_objStatus.StatusCode<>0 Then 
        Reachable = False 
    Else
 
        Reachable         = False
        set fn_objShell   = createobject("wscript.shell")
	Set fn_objFSO     = CreateObject("Scripting.FileSystemObject")
	strTempFile       = fn_objFSO.GetSpecialFolder(TemporaryFolder) & "\" & fn_objFSO.GetTempName
        fn_objShell.run     "cmd /c ping -a " & fn_objStatus.ProtocolAddress  & " > " & chr(34) & strTempFile & chr(34),0,true      
	Set results       = fn_objFSO.GetFile(strTempFile)
	set ts            = results.OpenAsTextStream(ForReading)
	do While ts.AtEndOfStream <> True
		retString = lcase(ts.ReadLine)
		if instr(retString, strHostName)>0 then
			Reachable = True
			exit do
		end if
	Loop
	ts.Close
        fn_objFSO.DeleteFile strTempFile
    End If
  Next
 
End Function

Permanent link to this article: https://www.vroom.cc/wordpress/the-advanced-ping/