Está en la página 1de 9

Ping y Trace route

1 de 9

Inicio

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

vb 6.0

Ocx - Activex

Api vb

Tutoriales - Manuales

Cdigo fuente

vb.net

Seccin de cdigo fuente Visual basic

Ping y Trace route


Dll Activex para realizar Ping y Trace mediante el Api winsock

Este cdigo fuente es un DLL Activex que


hice en base a unos ejemplos que tena
archivados, y que permitan realizar
mediante el uso de algunas funciones del
Api, principalmente la librera wsock32.dll,
un ping a un dominio y tambin un
TraceRoute.
La dll tiene 2 mtodos, uno llamado Ping y
otro Trace. A estos se le deben enviar como
parmetro un control TextBox o Label de
nuestro proyecto para mostrar el resultado
La dll compilada la pods descargar desde
este enlace. Dll Ping trace
propiedades que son:

Adems

de

dichos

mtodos,

tiene

NombreHost: en esta propiedad debemos indicar el nombre del dominio, puede ser
tambin la IP
nPaquetes: se debe establecer la cantidad de paquetes a enviar, el parmetro es opcional,
si no se especifica se enva por default un solo paquete
IPHost: Propiedad de solo lectura que contiene el valor, o mejor dicho la IP del Host

Pasos para crear la Dll Activex

1.
2.
3.
4.

Comenzar un proyecto de tipo Dll Activex.


Al mdulo de clase por defecto llamado class1 cambiarlo por: getPing
Agregar un mdulo .bas donde se definirn algunas funciones API, UDT y constantes.
Renombrar el proyecto (Proyecto1) por GPing o el que quieras (este nombre ser el que
aparecer luego cuando la referencies) ... o si no, pods establecrle el nomre que tendr,
desde el men proyecto > Propiedades de proyecto > descripcin del proyecto, como
est en la imagen:

07/10/2013 11:34

Ping y Trace route

2 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

Pegar el siguiente cdigo en el mdulo de clase


Texto plano Imprimir
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.

' WSock32 Variables


Dim
Dim
Dim
Dim
Dim
Dim

Ret As Long, sLowByte As String, sHighByte As String


sMsg As String, HostLen As Long, Host As String
Hostent As Hostent, PointerToPointer As Long, ListAddress As Long
WSAdata As WSAdata, DotA As Long, DotAddr As String, ListAddr As Long
MaxUDP As Long, MaxSockets As Long, i As Integer
Descripcion As String, Status As String

' ICMP Variables


Dim
Dim
Dim
Dim
Dim

bReturn As Boolean, hIP As Long


szBuffer As String
Addr As Long
Error As String
HostRespuesta As String

Dim TraceRT As Boolean


Dim TTL As Integer
'Variables para las propiedaes
Private m_NombreHost As String 'Nombre del Host
Private m_IPHost As String 'Ip del Host
Private m_nPaquetes As Byte 'Paquetes a enviar

'si se produce un error se manda al control de salida


Private Sub LeerError(ControlSalida As Object)
If
If
If
If
If
If
If
If
If
If
If
If
If
If
If
If
If

pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status
pIPe.Status

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

0 Then Error = "Success"


11001 Then Error = "Buffer too Small"
11002 Then Error = "Dest Network Not Reachable"
11003 Then Error = "Dest Host Not Reachable"
11004 Then Error = "Dest Protocol Not Reachable"
11005 Then Error = "Dest Port Not Reachable"
11006 Then Error = "No Resources Available"
11007 Then Error = "Bad Option"
11008 Then Error = "Hardware Error"
11009 Then Error = "Packet too Big"
11010 Then Error = "Rqst Timed Out"
11011 Then Error = "Bad Request"
11012 Then Error = "Bad Route"
11013 Then Error = "TTL Exprd in Transit"
11014 Then Error = "TTL Exprd Reassemb"
11015 Then Error = "Parameter Problem"
11016 Then Error = "Source Quench"

07/10/2013 11:34

Ping y Trace route

3 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.

If pIPe.Status = 11017
If pIPe.Status = 11018
If pIPe.Status = 11019
If pIPe.Status = 11020
If pIPe.Status = 11021
If pIPe.Status = 11022
If pIPe.Status = 11050
Error = Error + " (" +

Then Error = "Option too Big"


Then Error = " Bad Destination"
Then Error = "Address Deleted"
Then Error = "Spec MTU Change"
Then Error = "MTU Change"
Then Error = "Unload"
Then Error = "General Failure"
CStr(pIPe.Status) + ")"

DoEvents
If TraceRT = False Then
If pIPe.Status = 0 Then
ControlSalida = ControlSalida + " Replica de " + _
HostRespuesta + ":Bytes = " + Trim$(CStr(pIPe.DataSize)) _
+ " RTT = " + Trim$(CStr(pIPe.RoundTripTime)) + "ms TTL = " + _
Trim$(CStr(pIPe.Options.TTL)) + Chr$(13) + Chr$(10)
Else
ControlSalida = ControlSalida + " Replica de " + _
HostRespuesta + ": " + Error + Chr$(13) + Chr$(10)
End If
Else
If TTL - 1 < 10 Then ControlSalida = ControlSalida & " Hop # 0" + _
CStr(TTL - 1) Else ControlSalida = ControlSalida + " Hop # " + _
CStr(TTL - 1)
ControlSalida = ControlSalida + " " + HostRespuesta + Chr$(13) + _
Chr$(10)
End If
End Sub
'Recupera la Ip a partir del nombre de Host
Private Sub vbGetHostByName(m_NombreHost As String)
Dim szString As String
Host = Trim$(m_NombreHost)
szString = String(64, &H0)
Host = Host + Right$(szString, 64 - Len(Host))
If gethostbyname(Host) = SOCKET_ERROR Then
sMsg = "Winsock Error" & Str$(WSAGetLastError())
MsgBox sMsg, vbOKOnly, "Error"
Else
PointerToPointer = gethostbyname(Host)
CopyMemory Hostent.h_name, ByVal _
PointerToPointer, Len(Hostent)
ListAddress = Hostent.h_addr_list
CopyMemory ListAddr, ByVal ListAddress, 4
CopyMemory IPLong, ByVal ListAddr, 4
CopyMemory Addr, ByVal ListAddr, 4
m_IPHost = Trim$(CStr(Asc(IPLong.Byte4)) + "." + CStr(Asc(IPLong.Byte3)) _
+ "." + CStr(Asc(IPLong.Byte2)) + "." + CStr(Asc(IPLong.Byte1)))
End If
End Sub
'Recupera el nombre de Host
Private Sub vbGetHostName()
Host = String(64, &H0)
If gethostname(Host, HostLen) = SOCKET_ERROR Then
sMsg = "WSock32 Error" & Str$(WSAGetLastError())
MsgBox sMsg, vbOKOnly, "Error"
Else
Host = Left$(Trim$(Host), Len(Trim$(Host)) - 1)
m_NombreHost = Host
End If
End Sub
Private Sub vbIcmpSendEcho(ControlSalida As Object)
Dim NbrOfPkts As Integer
szBuffer = "abcdefghijklmnopqrstuvwabcdefghijklmnopqrstu" & _
"vwabcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvwabcdefghij" & _
"klmnopqrstuvwabcdefghijklm"

07/10/2013 11:34

Ping y Trace route

4 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.

szBuffer = Left$(szBuffer, Val("32"))


If IsNumeric(m_nPaquetes) Then
If Val(m_nPaquetes) < 1 Then m_nPaquetes = "1"
Else
m_nPaquetes = "1"
End If
If TraceRT = True Then m_nPaquetes = "1"
For NbrOfPkts = 1 To Trim$(m_nPaquetes)
DoEvents
bReturn = IcmpSendEcho(hIP, Addr, szBuffer, Len(szBuffer), _
pIPo, pIPe, Len(pIPe) + 8, 2700)
If bReturn Then
HostRespuesta = CStr(pIPe.Address(0)) + "." + CStr(pIPe.Address(1)) _
+ "." + CStr(pIPe.Address(2)) + "." + CStr(pIPe.Address(3))
LeerError ControlSalida
Else
If TraceRT Then
TTL = TTL - 1
Else
' Tiempo agotado
ControlSalida = ControlSalida & _
"Tiempo de espera agotado para la solicitud" & Chr$(13) _
+ Chr$(10)
End If
End If
Next NbrOfPkts
If Not TraceRT Then
ControlSalida = ControlSalida & Chr(13) & Chr(10) & "-----------------" & _
Chr(13) & Chr(10)
End If
End Sub

'Inicializa el Wsock32
Private Sub vbWSAStartup()
Ret = WSAStartup(&H101, WSAdata)
If Ret <> 0 Then
MsgBox "WSock32.dll no responde!", vbOKOnly, "VB4032-ICMPEcho"
End If
If LoByte(WSAdata.wVersion) < WS_VERSION_MAJOR Or _
(LoByte(WSAdata.wVersion) = WS_VERSION_MAJOR _
And HiByte(WSAdata.wVersion) < WS_VERSION_MINOR) Then
sHighByte = Trim$(Str$(HiByte(WSAdata.wVersion)))
sLowByte = Trim$(Str$(LoByte(WSAdata.wVersion)))
sMsg = "Version de WinSock " & sLowByte & "." & sHighByte
sMsg = sMsg & " No soportado "
MsgBox sMsg, vbOKOnly, "Error"
Exit Sub
End If
If WSAdata.iMaxSockets < MIN_SOCKETS_REQD Then
sMsg = "Esta aplicacin requiere un minimo de "
sMsg = sMsg & Trim$(Str$(MIN_SOCKETS_REQD)) & " sockets soportados."
MsgBox sMsg, vbOKOnly, "Error"
Exit Sub
End If
MaxSockets = WSAdata.iMaxSockets
If MaxSockets < 0 Then
MaxSockets = 65536 + MaxSockets
End If
MaxUDP = WSAdata.iMaxUdpDg
If MaxUDP < 0 Then
MaxUDP = 65536 + MaxUDP
End If
Descripcion = ""

07/10/2013 11:34

Ping y Trace route

5 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.

For i = 0 To WSADESCRIPTION_LEN
If WSAdata.szDescription(i) = 0 Then Exit For
Descripcion = Descripcion + Chr$(WSAdata.szDescription(i))
Next i
Status = ""
For i = 0 To WSASYS_STATUS_LEN
If WSAdata.szSystemStatus(i) = 0 Then Exit For
Status = Status + Chr$(WSAdata.szSystemStatus(i))
Next i
End Sub
Private Function HiByte(ByVal wParam As Integer)
HiByte = wParam \ &H100 And &HFF&
End Function
Private Function LoByte(ByVal wParam As Integer)
LoByte = wParam And &HFF&
End Function
Private Sub vbWSACleanup()
Ret = WSACleanup()
If Ret <> 0 Then
sMsg = "WSock32 Error - " & Trim$(Str$(Ret)) & " occurred in Cleanup"
MsgBox sMsg, vbOKOnly, "Error"
Exit Sub
End If
End Sub
Private Sub vbIcmpCloseHandle()
bReturn = IcmpCloseHandle(hIP)
If bReturn = False Then
MsgBox "Error", vbOKOnly, "Error"
End If
End Sub
Private Sub vbIcmpCreateFile()
hIP = IcmpCreateFile()
If hIP = 0 Then
MsgBox "Unable to Create File Handle", vbOKOnly, "VBPing32"
End If
End Sub
Public Sub Ping(ControlSalida As Object, Optional TTL As Byte = 255)
'Initializa el Winsock
vbWSAStartup
If Len(m_NombreHost) = 0 Then
vbGetHostName
End If
If m_NombreHost = "" Then
MsgBox "No se especifico un nombre de Host!", vbOKOnly, "Error"
vbWSACleanup
Exit Sub
End If
'Recupera la IP del Host
vbGetHostByName m_NombreHost
vbIcmpCreateFile
If IsNumeric(TTL) Then
If (Val(TTL) > 255) Then TTL = "255"
If (Val(TTL) < 2) Then TTL = "2"
Else
TTL = "255"
End If
pIPo.TTL = Trim$(CStr(TTL))
'Enva el ICMP Echo al control de salida
vbIcmpSendEcho ControlSalida
'Cierra ICMP Handle
vbIcmpCloseHandle

07/10/2013 11:34

Ping y Trace route

6 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.

' Finaliza el Winsock


vbWSACleanup
End Sub
Public Sub Trace(ControlSalida As Object, Optional TTL As Byte = 255)
'Initializa el Winsock
vbWSAStartup
If Len(m_NombreHost) = 0 Then
vbGetHostName
End If
If m_NombreHost = "" Then
MsgBox "No se especifico un Host!", vbOKOnly, "Error"
vbWSACleanup
Exit Sub
End If
vbGetHostByName m_NombreHost
'recupera el Handle ICMP
vbIcmpCreateFile
TraceRT = True
'Mostramos los resultados en el control de salida
ControlSalida = ControlSalida + "Tracing Route to " + m_IPHost + _
":" + Chr$(13) + Chr$(10) + Chr$(13) + Chr$(10)
For TTL = 2 To 255
pIPo.TTL = TTL
''Mostramos los resultados en el control de salida (ICMP Echo Request)
vbIcmpSendEcho ControlSalida
DoEvents
If HostRespuesta = m_IPHost Then
ControlSalida = ControlSalida + Chr$(13) + Chr$(10) + _
"Route Trace finalizado" + Chr$(13) + Chr$(10) + Chr$(13) + Chr$(10)
Exit For
End If
Next TTL
TraceRT = False
' Cierra the ICMP Handle
vbIcmpCloseHandle
' Finaliza el Winsock
vbWSACleanup
End Sub
'Para el nomber del Host
Public Property Get NombreHost() As String
NombreHost = m_NombreHost
End Property
Public Property Let NombreHost(ByVal vNewValue As String)
m_NombreHost = vNewValue
End Property
'Almacena la Ip del Host
Public Property Get IPHost() As Variant
IPHost = m_IPHost
End Property
Public Property Let IPHost(ByVal vNewValue As Variant)
MsgBox "La propiedad es de solo lectura", vbInformation
End Property
'Almacena la Cantidad de paquetes a enviar
Public Property Get nPaquetes() As Byte
nPaquetes = m_nPaquetes
End Property
Public Property Let nPaquetes(ByVal vNewValue As Byte)
m_nPaquetes = vNewValue
End Property

07/10/2013 11:34

Ping y Trace route

7 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

Colocar el siguiente cdigo en el mdulo .bas


Texto plano Imprimir
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.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.

' Constantess para wsock32


Const WS_VERSION_MAJOR = &H101 \ &H100 And &HFF&
Const WS_VERSION_MINOR = &H101 And &HFF&
Const MIN_SOCKETS_REQD = 0

' Estructuras para el WSock32


Type Inet_address
Byte4 As String
Byte3 As String
Byte2 As String
Byte1 As String
End Type

*
*
*
*

1
1
1
1

Public IPLong As Inet_address


Type WSAdata
wVersion As Integer
wHighVersion As Integer
szDescription(0 To 255) As Byte
szSystemStatus(0 To 128) As Byte
iMaxSockets As Integer
iMaxUdpDg As Integer
lpVendorInfo As Long
End Type
Type Hostent
h_name As Long
h_aliases As Long
h_addrtype As Integer
h_length As Integer
h_addr_list As Long
End Type
Type IP_OPTION_INFORMATION
TTL As Byte
Tos As Byte
Flags As Byte
OptionsSize As Long
OptionsData As String * 128
End Type

'
'
'
'
'

Time to Live (used for traceroute)


Type of Service (usually 0)
IP header Flags (usually 0)
Size of Options data (usually 0, max 40)
Options data buffer

Public pIPo As IP_OPTION_INFORMATION


Type IP_ECHO_REPLY
Address(0 To 3) As Byte
Status As Long
RoundTripTime As Long
DataSize As Integer
Reserved As Integer
data As Long
Options As IP_OPTION_INFORMATION
End Type

'
'
'
'
'
'
'

Replying Address
Reply Status
Round Trip Time in milliseconds
reply data size
for system use
pointer to echo data
Reply Options

Public pIPe As IP_ECHO_REPLY


'Api que Obtiene el nombre de Host
Declare Function gethostname Lib "wsock32.dll" (ByVal hostname$, HostLen&) As Long
'Api que Obtiene La IP a partir del nombre de Host
Declare Function gethostbyname& Lib "wsock32.dll" (ByVal hostname$)
Declare Function WSAGetLastError Lib "wsock32.dll" () As Long
'Api para inicializar wsock32
Declare Function WSAStartup Lib "wsock32.dll" (ByVal wVersionRequired&, lpWSAData As
'Api para finalizar wsock32
Declare Function WSACleanup Lib "wsock32.dll" () As Long

Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource
ByVal cbCopy As Long)
Declare Function IcmpCreateFile Lib "icmp.dll" () As Long
Declare Function IcmpCloseHandle Lib "icmp.dll" (ByVal HANDLE As Long) As Boolean
Declare Function IcmpSendEcho Lib "ICMP" (ByVal IcmpHandle As Long, ByVal DestAddress
ByVal RequestData As String, ByVal RequestSize As Integer, RequestOptns As IP_OPTION_INFORMATIO
ReplyBuffer As IP_ECHO_REPLY, ByVal ReplySize As Long, ByVal TimeOut As Long)

07/10/2013 11:34

Ping y Trace route

8 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

Generar la Dll e incluirla en un proyecto Exe

Ahora compilar la Dll desde el men Archivo. Una ves generada, crear un proyecto de tipo
Exe estndar para probarla.

Colocar los siguientes controles en un formulario:


Text1: ac se indica el nombre del Host (propiedad NombreHost)
Text2: Se indica elnmero de paquetes a enviar (Propiedad NPaquetes)
txtSalida: Ac se visualiza el resultado del Ping o el TRace. Este TextBox colocar el
Multiline en true y la propiedad ScrollBar en Vertical
Command1: este ejcutar el Mtodo Ping
Command2: Ejecuta el mtodo Trace

Los controles quedarn similares a los de la siguiente grfico:

Desde el men Proyecto > Referencias , aadir la dll generada.

El cdigo del Formulario


Texto plano Imprimir
1.
2.
3.
4.
5.
6.
7.
8.
9.

Option Explicit
Dim clsPing As getPing
'Ping
''''''''''''''''''''''''''''
Private Sub Command1_Click()
With clsPing
.NombreHost = Text1 'Host

07/10/2013 11:34

Ping y Trace route

9 de 9

http://www.recursosvisualbasic.com.ar/htm/utilidades-codigo-fuente/dl...

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.

.nPaquetes = Text2 'Cantidad de paquetes


.Ping txtsalida 'Control de salida
End With
End Sub
'Trace
'''''''''''''''''''''''''''''
Private Sub Command2_Click()
With clsPing
.NombreHost = Text1 'Host
.Trace txtsalida 'Control de salida
End With
End Sub
Private Sub Form_Load()
'Creamos la referencia
Set clsPing = New getPing
End Sub
Private Sub Form_Unload(Cancel As Integer)
'Eliminamos
If Not clsPing Is Nothing Then
Set clsPing = Nothing
End If
End Sub

Buscar en Recursos vb

Download Android Apps


MoboGenie.com/Download-Android-Apps

Largest Collection of Android Apps. Save Data Cost. Try Mobogenie Now!
visual basic - Buscar
www.recursosvisualbasic.com.ar
Recursos

Privacidad

Copyright

2005

2009

07/10/2013 11:34

También podría gustarte