Autor Tema: Comprobar conexión a internet.  (Leído 15251 veces)

0 Usuarios y 1 Visitante están viendo este tema.

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #15 en: Noviembre 26, 2012, 04:48:06 pm »
Es desde una maquina virtual amigo

Si, y simula perfectamente cuando tienes el router y todo ok pero tu proveedor de internet no te provee internet. Por eso comentaba que prueben este tema dentro de una maquina virtual.
Me encuentras en YAcosta.com

E N T E R

  • Petabyte
  • ******
  • Mensajes: 1062
  • Reputación: +57/-13
  • www.enterpy.com
    • Ver Perfil
    • www.enterpy.com
Re:Comprobar conexión a internet.
« Respuesta #16 en: Noviembre 26, 2012, 06:03:25 pm »
Cuando dije es una maquina virtual te estaba diciendo que tambien lo probe en una maquina virtual.

Aca te dejo una captura desde el celular mientras los estaba probando.

[youtube]http://www.youtube.com/watch?v=RtUGiEIeBPI&feature=youtu.be[/youtube]
CIBER GOOGLE - CONCEPCIÓN PARAGUAY
www.enterpy.com
Primera regla de la programacion, para que vas a hacerlo complicado si lo puedes hacer sencillo

LeandroA

  • Administrador
  • Petabyte
  • *****
  • Mensajes: 1128
  • Reputación: +151/-8
    • Ver Perfil
Re:Comprobar conexión a internet.
« Respuesta #17 en: Noviembre 26, 2012, 07:00:51 pm »
Yvan en cuanto lo tenes al timer?, se me hace que no se descarga el objeto., otra cosa que se pasaba por alto es cancelar el blucle en caso de cerrar el form

aver proba asi, no cambia mucho solo aumento el timer
Código: [Seleccionar]
Option Explicit
Dim bCancel As Long

Public Function CheckConnection(sURL) As Boolean
  Dim xml As Object
  Dim lTime As Long
  Set xml = CreateObject("Microsoft.XMLHTTP")
  xml.Open "GET", sURL, True
  xml.Send
 
  bCancel = False
 
  lTime = Timer
  Do While xml.readyState <> 4
    If bCancel Then Exit Function
    DoEvents
 
    If lTime + 10 < Timer Then '5 Segundos de espera
      CheckConnection = False
      Set xml = Nothing
      Exit Function
    End If
   
  Loop
 
  CheckConnection = CBool(xml.Status = 0)
  Set xml = Nothing
End Function
 
Private Sub Form_Load()
   
    Timer1.Interval = 12000
End Sub

Private Sub Form_Unload(Cancel As Integer)
    bCancel = True
End Sub

Private Sub Timer1_Timer()
    If CheckConnection("http://www.google.com/") Then
       Label1 = "Hay Internet"
    Else
       Label1 = "No Hay Internet"
    End If
End Sub

estoy casi seguro que tenes el timer mas rapido que el tiempo de espera.
« última modificación: Noviembre 26, 2012, 07:04:39 pm por LeandroA »

E N T E R

  • Petabyte
  • ******
  • Mensajes: 1062
  • Reputación: +57/-13
  • www.enterpy.com
    • Ver Perfil
    • www.enterpy.com
Re:Comprobar conexión a internet.
« Respuesta #18 en: Noviembre 26, 2012, 08:19:59 pm »
Este es otro metodo tambien me funciona muy bien hace ping constantemente a un ip determinado. y si todo va bien dice OK, o sino lista los errores posibles.

FUENTE: http://support.microsoft.com/kb/300197/es

EN UN MODULO.

Código: (VB) [Seleccionar]
Option Explicit

'Icmp constants converted from
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pingstatus.asp

Private Const ICMP_SUCCESS As Long = 0
Private Const ICMP_STATUS_BUFFER_TO_SMALL = 11001                   'Buffer Too Small
Private Const ICMP_STATUS_DESTINATION_NET_UNREACH = 11002           'Destination Net Unreachable
Private Const ICMP_STATUS_DESTINATION_HOST_UNREACH = 11003          'Destination Host Unreachable
Private Const ICMP_STATUS_DESTINATION_PROTOCOL_UNREACH = 11004      'Destination Protocol Unreachable
Private Const ICMP_STATUS_DESTINATION_PORT_UNREACH = 11005          'Destination Port Unreachable
Private Const ICMP_STATUS_NO_RESOURCE = 11006                       'No Resources
Private Const ICMP_STATUS_BAD_OPTION = 11007                        'Bad Option
Private Const ICMP_STATUS_HARDWARE_ERROR = 11008                    'Hardware Error
Private Const ICMP_STATUS_LARGE_PACKET = 11009                      'Packet Too Big
Private Const ICMP_STATUS_REQUEST_TIMED_OUT = 11010                 'Request Timed Out
Private Const ICMP_STATUS_BAD_REQUEST = 11011                       'Bad Request
Private Const ICMP_STATUS_BAD_ROUTE = 11012                         'Bad Route
Private Const ICMP_STATUS_TTL_EXPIRED_TRANSIT = 11013               'TimeToLive Expired Transit
Private Const ICMP_STATUS_TTL_EXPIRED_REASSEMBLY = 11014            'TimeToLive Expired Reassembly
Private Const ICMP_STATUS_PARAMETER = 11015                         'Parameter Problem
Private Const ICMP_STATUS_SOURCE_QUENCH = 11016                     'Source Quench
Private Const ICMP_STATUS_OPTION_TOO_BIG = 11017                    'Option Too Big
Private Const ICMP_STATUS_BAD_DESTINATION = 11018                   'Bad Destination
Private Const ICMP_STATUS_NEGOTIATING_IPSEC = 11032                 'Negotiating IPSEC
Private Const ICMP_STATUS_GENERAL_FAILURE = 11050                   'General Failure

Public Const WINSOCK_ERROR = "Windows Sockets not responding correctly."
Public Const INADDR_NONE As Long = &HFFFFFFFF
Public Const WSA_SUCCESS = 0
Public Const WS_VERSION_REQD As Long = &H101

'Clean up sockets.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512

Private Declare Function WSACleanup Lib "WSOCK32.DLL" () As Long

'Open the socket connection.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Private Declare Function WSAStartup Lib "WSOCK32.DLL" (ByVal wVersionRequired As Long, lpWSADATA As WSADATA) As Long

'Create a handle on which Internet Control Message Protocol (ICMP) requests can be issued.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmpcreatefile.asp
Private Declare Function IcmpCreateFile Lib "icmp.dll" () As Long

'Convert a string that contains an (Ipv4) Internet Protocol dotted address into a correct address.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_4esy.asp
Private Declare Function inet_addr Lib "WSOCK32.DLL" (ByVal cp As String) As Long

'Close an Internet Control Message Protocol (ICMP) handle that IcmpCreateFile opens.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmpclosehandle.asp

Private Declare Function IcmpCloseHandle Lib "icmp.dll" (ByVal IcmpHandle As Long) As Long

'Information about the Windows Sockets implementation
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Private Type WSADATA
   wVersion As Integer
   wHighVersion As Integer
   szDescription(0 To 256) As Byte
   szSystemStatus(0 To 128) As Byte
   iMaxSockets As Long
   iMaxUDPDG As Long
   lpVendorInfo As Long
End Type

'Send an Internet Control Message Protocol (ICMP) echo request, and then return one or more replies.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcetcpip/htm/cerefIcmpSendEcho.asp
Private Declare Function IcmpSendEcho Lib "icmp.dll" (ByVal IcmpHandle As Long, ByVal DestinationAddress As Long, ByVal RequestData As String, ByVal RequestSize As Long, ByVal RequestOptions As Long, ReplyBuffer As ICMP_ECHO_REPLY, ByVal ReplySize As Long, ByVal Timeout As Long) As Long
 
'This structure describes the options that will be included in the header of an IP packet.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcetcpip/htm/cerefIP_OPTION_INFORMATION.asp
Private Type IP_OPTION_INFORMATION
   Ttl             As Byte
   Tos             As Byte
   Flags           As Byte
   OptionsSize     As Byte
   OptionsData     As Long
End Type

'This structure describes the data that is returned in response to an echo request.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmp_echo_reply.asp
Public Type ICMP_ECHO_REPLY
   address         As Long
   Status          As Long
   RoundTripTime   As Long
   DataSize        As Long
   Reserved        As Integer
   ptrData                 As Long
   Options        As IP_OPTION_INFORMATION
   Data            As String * 250
End Type

'-- Ping a string representation of an IP address.
' -- Return a reply.
' -- Return long code.
Public Function ping(sAddress As String, Reply As ICMP_ECHO_REPLY) As Long

Dim hIcmp As Long
Dim lAddress As Long
Dim lTimeOut As Long
Dim StringToSend As String

'Short string of data to send
StringToSend = "hello"

'ICMP (ping) timeout
lTimeOut = 1000 'ms

'Convert string address to a long representation.
lAddress = inet_addr(sAddress)

If (lAddress <> -1) And (lAddress <> 0) Then
       
    'Create the handle for ICMP requests.
    hIcmp = IcmpCreateFile()
   
    If hIcmp Then
        'Ping the destination IP address.
        Call IcmpSendEcho(hIcmp, lAddress, StringToSend, Len(StringToSend), 0, Reply, Len(Reply), lTimeOut)

        'Reply status
        ping = Reply.Status
       
        'Close the Icmp handle.
        IcmpCloseHandle hIcmp
    Else
        Debug.Print "failure opening icmp handle."
        ping = -1
    End If
Else
    ping = -1
End If

End Function

'Clean up the sockets.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Public Sub SocketsCleanup()
   
   WSACleanup
   
End Sub

'Get the sockets ready.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Public Function SocketsInitialize() As Boolean

   Dim WSAD As WSADATA

   SocketsInitialize = WSAStartup(WS_VERSION_REQD, WSAD) = ICMP_SUCCESS

End Function

'Convert the ping response to a message that you can read easily from constants.
'For more information about these constants, visit the following Microsoft Web site:
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pingstatus.asp

Public Function EvaluatePingResponse(PingResponse As Long) As String

  Select Case PingResponse
   
  'Success
  'Case ICMP_SUCCESS: EvaluatePingResponse = "Success!"
  Case ICMP_SUCCESS: EvaluatePingResponse = "OK"
           
  'Some error occurred
  Case ICMP_STATUS_BUFFER_TO_SMALL:    EvaluatePingResponse = "Buffer Too Small"
  Case ICMP_STATUS_DESTINATION_NET_UNREACH: EvaluatePingResponse = "Destination Net Unreachable"
  Case ICMP_STATUS_DESTINATION_HOST_UNREACH: EvaluatePingResponse = "Destination Host Unreachable"
  Case ICMP_STATUS_DESTINATION_PROTOCOL_UNREACH: EvaluatePingResponse = "Destination Protocol Unreachable"
  Case ICMP_STATUS_DESTINATION_PORT_UNREACH: EvaluatePingResponse = "Destination Port Unreachable"
  Case ICMP_STATUS_NO_RESOURCE: EvaluatePingResponse = "No Resources"
  Case ICMP_STATUS_BAD_OPTION: EvaluatePingResponse = "Bad Option"
  Case ICMP_STATUS_HARDWARE_ERROR: EvaluatePingResponse = "Hardware Error"
  Case ICMP_STATUS_LARGE_PACKET: EvaluatePingResponse = "Packet Too Big"
  Case ICMP_STATUS_REQUEST_TIMED_OUT: EvaluatePingResponse = "Request Timed Out"
  Case ICMP_STATUS_BAD_REQUEST: EvaluatePingResponse = "Bad Request"
  Case ICMP_STATUS_BAD_ROUTE: EvaluatePingResponse = "Bad Route"
  Case ICMP_STATUS_TTL_EXPIRED_TRANSIT: EvaluatePingResponse = "TimeToLive Expired Transit"
  Case ICMP_STATUS_TTL_EXPIRED_REASSEMBLY: EvaluatePingResponse = "TimeToLive Expired Reassembly"
  Case ICMP_STATUS_PARAMETER: EvaluatePingResponse = "Parameter Problem"
  Case ICMP_STATUS_SOURCE_QUENCH: EvaluatePingResponse = "Source Quench"
  Case ICMP_STATUS_OPTION_TOO_BIG: EvaluatePingResponse = "Option Too Big"
  Case ICMP_STATUS_BAD_DESTINATION: EvaluatePingResponse = "Bad Destination"
  Case ICMP_STATUS_NEGOTIATING_IPSEC: EvaluatePingResponse = "Negotiating IPSEC"
  Case ICMP_STATUS_GENERAL_FAILURE: EvaluatePingResponse = "General Failure"
           
  'Unknown error occurred
  Case Else: EvaluatePingResponse = "Unknown Response"
       
  End Select

End Function


EN UN FORMULARIO.

Código: (VB) [Seleccionar]
Private Sub Timer1_Timer()
   
    Dim Reply As ICMP_ECHO_REPLY
    Dim lngSuccess As Long
    Dim strIPAddress As String
   
    'Get the sockets ready.
    If SocketsInitialize() Then
   
        'Address to ping
        strIPAddress = "173.194.37.19"  'IP GOOGLE
        lngSuccess = ping(strIPAddress, Reply)
       
        If EvaluatePingResponse(lngSuccess) = "OK" Then
            Picture1.BackColor = vbGreen
        Else
            Picture1.BackColor = vbRed
        End If
       
        'Clean up the sockets.
        SocketsCleanup
       
    Else
   
        Debug.Print WINSOCK_ERROR
   
    End If
   
End Sub
CIBER GOOGLE - CONCEPCIÓN PARAGUAY
www.enterpy.com
Primera regla de la programacion, para que vas a hacerlo complicado si lo puedes hacer sencillo

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #19 en: Noviembre 27, 2012, 12:08:28 am »
Cuando dije es una maquina virtual te estaba diciendo que tambien lo probe en una maquina virtual.

Aca te dejo una captura desde el celular mientras los estaba probando.


Si mi broder, efectivamente tienes razon, voy a volver a revisar todo a ver que esta pasando.
Me encuentras en YAcosta.com

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #20 en: Noviembre 27, 2012, 12:54:48 am »
Yvan en cuanto lo tenes al timer?, se me hace que no se descarga el objeto., otra cosa que se pasaba por alto es cancelar el blucle en caso de cerrar el form
...

estoy casi seguro que tenes el timer mas rapido que el tiempo de espera.

Saludos doc, buenas y malas noticias. Efectivamente tenia el timer en 1000 de interval. Lo cambie a 12,000 y use el ultimo código que publicas, ejecute y lamentablemente sigo teniendo el mismo efecto, osea cuando cierro y ejecuto el proyecto ya teniendo el internet restaurado me sigue saliendo "No hay Internet" y solo se restablece si cierro el VB6 como mostré en el ultimo video.

Probare también lo del ping que comenta Enter.
Me encuentras en YAcosta.com

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #21 en: Noviembre 27, 2012, 02:19:32 am »
Este es otro metodo tambien me funciona muy bien hace ping constantemente a un ip determinado. y si todo va bien dice OK, o sino lista los errores posibles.
....

No amigo, no me resulto, gracias por darme una mano, pero no me resulto, no lo he probado totalmente, es mas ni siquiera apague el router porque ni bien ejecute el codigo el formulario se relentiza demasiado, osea, esta cambiando de rojo a verde (no se porque) y mientras voy escribiendo en un textbox, lo que voy escribiendo se frena o se congela y luego aparece el texto que escribi, por eso no profundice mas en este aporte. Igual muchas gracias por tu tiempo, pero voy a usar el ultimo codigo de Leandro que al menos me cubre en un alto porcentaje la solución del problema.

Muchas gracias.
Me encuentras en YAcosta.com

E N T E R

  • Petabyte
  • ******
  • Mensajes: 1062
  • Reputación: +57/-13
  • www.enterpy.com
    • Ver Perfil
    • www.enterpy.com
Re:Comprobar conexión a internet.
« Respuesta #22 en: Noviembre 27, 2012, 08:13:31 am »
Que raro che por que como te mostré en el vídeo la 2da opción me funciona bastante bien desactivando las redes, volviendo a activar y por ultimo apagando y prendiendo el router directamente.
CIBER GOOGLE - CONCEPCIÓN PARAGUAY
www.enterpy.com
Primera regla de la programacion, para que vas a hacerlo complicado si lo puedes hacer sencillo

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #23 en: Noviembre 27, 2012, 12:03:15 pm »
¿Pero chequeaste poniendo un textbox por ejemplo y mientras se ejecuta ese programa ir escribiendo? Es alli donde se frena lo que uno escribe.
Me encuentras en YAcosta.com

Psyke1

  • Megabyte
  • ***
  • Mensajes: 130
  • Reputación: +11/-7
  • VBManiac
    • Ver Perfil
    • h-Sec
Re:Comprobar conexión a internet.
« Respuesta #24 en: Noviembre 27, 2012, 01:48:18 pm »
Creo que el Timer se está ahogando:P

Yo suelo desactivar los Timers al inicio del evento Timer() y los activo al final del mismo. De este modo no damos a nuestro PC tanto trabajo. Además, teniendo en cuenta que lo pruebas en una VM, le costará más.  :-\

Prueba así (fíjate en las líneas destacadas):
Código: (vb,11,19) [Seleccionar]
Option Explicit
Private Declare Function InternetCheckConnectionA Lib "wininet.dll" (ByVal lpszUrl As String, ByVal dwFlags As Long, ByVal dwReserved As Long) As Long

Private Const FLAG_ICC_FORCE_CONNECTION  As Long = &H1

Public Function IsInternetOn() As Boolean
    IsInternetOn = InternetCheckConnectionA("http://www.google.com/", FLAG_ICC_FORCE_CONNECTION, 0&)
End Function

Private Sub Timer1_Timer()
    Timer1.Enabled = False

    If IsInternetOn Then
       Label1 = "Hay Internet"
    Else
       Label1 = "No Hay Internet"
    End If

    Timer1.Enabled = True
End Sub

DoEvents! :P
« última modificación: Noviembre 27, 2012, 01:57:50 pm por Psyke1 »

YAcosta

  • Moderador Global
  • Exabyte
  • *****
  • Mensajes: 2853
  • Reputación: +160/-38
  • Daddy de Qüentas y QüeryFull
    • Ver Perfil
    • Personal
Re:Comprobar conexión a internet.
« Respuesta #25 en: Noviembre 27, 2012, 02:54:12 pm »
Saludos Psyke1.

Probé tu código tal cual (proyecto nuevo como todos los anteriores), pero creo que ya empezaré a tirar lo toalla porque al parecer debe tratarse de alguna excepción en vista que a todos le funciona al 100 pero a mi no, e imagino que es algo que deba ver con mi maquina virtual, luego armaré otra y probaré en ella.

(El timer lo puse a 12 segundos y use tu código)

Estos fueron los resultados y los ejecuté en este orden, cada cambio lo mencionaré.
Con el programa en ejecución:
1.- Detectó conexión a internet: OK
2.- Deshabilité la red la maquina virtual: No hay Internet:  OK
3.- Habilite la red y el programa lo reconoció: OK
4.- Desconecte el router y el label siguió con Hay Internet: Espere 2 minutos e igual, debugee y IsInternetOn me sigue dando true a pesar de estar el router apagado.

Detuve el programa y lo volví a ejecutar (ojo, sigue router apagado)
5.- El programa se colgó y se colgó feo. Quedo congelado y luego de un rato me detecto que no hay internet pero siguió quedándose colgado. Lo tuve que detener en la primera que me dejo hacerlo.

Prendí el router
6.- Ejecute el programa y me reconoció el internet. A diferencia de los códigos anteriores esta vez no fue necesario cerrar el VB6 para el segundo intento.

Este código no presento el problema de no operar bien en el segundo intento y me obligaba a cerrar el VB6 pero me cuelga cuando no hay internet, motivo inicial de este post.

Gracias por tu tiempo






 
Me encuentras en YAcosta.com

SKL

  • Administrador
  • Kilobyte
  • *****
  • Mensajes: 52
  • Reputación: +9/-2
  • GRIPE A
    • Ver Perfil
Re:Comprobar conexión a internet.
« Respuesta #26 en: Mayo 24, 2014, 07:26:41 pm »
Esto es viejo pero parece que aun no esta resuelto.... yo tengo una manera que es haciendole PING a la pagina. esta bueno y no genera el problema que tenes....

Aca va >>


Esto en un Modulo !!!
Código: [Seleccionar]
Option Explicit

Public Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Public Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

'Icmp constants converted from
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pingstatus.asp

Private Const ICMP_SUCCESS As Long = 0
Private Const ICMP_STATUS_BUFFER_TO_SMALL = 11001                   'Buffer Too Small
Private Const ICMP_STATUS_DESTINATION_NET_UNREACH = 11002           'Destination Net Unreachable
Private Const ICMP_STATUS_DESTINATION_HOST_UNREACH = 11003          'Destination Host Unreachable
Private Const ICMP_STATUS_DESTINATION_PROTOCOL_UNREACH = 11004      'Destination Protocol Unreachable
Private Const ICMP_STATUS_DESTINATION_PORT_UNREACH = 11005          'Destination Port Unreachable
Private Const ICMP_STATUS_NO_RESOURCE = 11006                       'No Resources
Private Const ICMP_STATUS_BAD_OPTION = 11007                        'Bad Option
Private Const ICMP_STATUS_HARDWARE_ERROR = 11008                    'Hardware Error
Private Const ICMP_STATUS_LARGE_PACKET = 11009                      'Packet Too Big
Private Const ICMP_STATUS_REQUEST_TIMED_OUT = 11010                 'Request Timed Out
Private Const ICMP_STATUS_BAD_REQUEST = 11011                       'Bad Request
Private Const ICMP_STATUS_BAD_ROUTE = 11012                         'Bad Route
Private Const ICMP_STATUS_TTL_EXPIRED_TRANSIT = 11013               'TimeToLive Expired Transit
Private Const ICMP_STATUS_TTL_EXPIRED_REASSEMBLY = 11014            'TimeToLive Expired Reassembly
Private Const ICMP_STATUS_PARAMETER = 11015                         'Parameter Problem
Private Const ICMP_STATUS_SOURCE_QUENCH = 11016                     'Source Quench
Private Const ICMP_STATUS_OPTION_TOO_BIG = 11017                    'Option Too Big
Private Const ICMP_STATUS_BAD_DESTINATION = 11018                   'Bad Destination
Private Const ICMP_STATUS_NEGOTIATING_IPSEC = 11032                 'Negotiating IPSEC
Private Const ICMP_STATUS_GENERAL_FAILURE = 11050                   'General Failure

Public Const WINSOCK_ERROR = "Windows Sockets not responding correctly."
Public Const INADDR_NONE As Long = &HFFFFFFFF
Public Const WSA_SUCCESS = 0
Public Const WS_VERSION_REQD As Long = &H101

'Clean up sockets.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512

Private Declare Function WSACleanup Lib "WSOCK32.DLL" () As Long

'Open the socket connection.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Private Declare Function WSAStartup Lib "WSOCK32.DLL" (ByVal wVersionRequired As Long, lpWSADATA As WSADATA) As Long

'Create a handle on which Internet Control Message Protocol (ICMP) requests can be issued.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmpcreatefile.asp
Private Declare Function IcmpCreateFile Lib "icmp.dll" () As Long

'Convert a string that contains an (Ipv4) Internet Protocol dotted address into a correct address.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_4esy.asp
Private Declare Function inet_addr Lib "WSOCK32.DLL" (ByVal cp As String) As Long

'Close an Internet Control Message Protocol (ICMP) handle that IcmpCreateFile opens.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmpclosehandle.asp

Private Declare Function IcmpCloseHandle Lib "icmp.dll" (ByVal IcmpHandle As Long) As Long

'Information about the Windows Sockets implementation
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Private Type WSADATA
   wVersion As Integer
   wHighVersion As Integer
   szDescription(0 To 256) As Byte
   szSystemStatus(0 To 128) As Byte
   iMaxSockets As Long
   iMaxUDPDG As Long
   lpVendorInfo As Long
End Type

'Send an Internet Control Message Protocol (ICMP) echo request, and then return one or more replies.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcetcpip/htm/cerefIcmpSendEcho.asp
Private Declare Function IcmpSendEcho Lib "icmp.dll" _
   (ByVal IcmpHandle As Long, _
    ByVal DestinationAddress As Long, _
    ByVal RequestData As String, _
    ByVal RequestSize As Long, _
    ByVal RequestOptions As Long, _
    ReplyBuffer As ICMP_ECHO_REPLY, _
    ByVal ReplySize As Long, _
    ByVal Timeout As Long) As Long
 
'This structure describes the options that will be included in the header of an IP packet.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcetcpip/htm/cerefIP_OPTION_INFORMATION.asp
Private Type IP_OPTION_INFORMATION
   Ttl             As Byte
   Tos             As Byte
   Flags           As Byte
   OptionsSize     As Byte
   OptionsData     As Long
End Type

'This structure describes the data that is returned in response to an echo request.
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcesdkr/htm/_wcesdk_icmp_echo_reply.asp
Public Type ICMP_ECHO_REPLY
   address         As Long
   Status          As Long
   RoundTripTime   As Long
   DataSize        As Long
   Reserved        As Integer
   ptrData                 As Long
   Options        As IP_OPTION_INFORMATION
   Data            As String * 250
End Type

'-- Ping a string representation of an IP address.
' -- Return a reply.
' -- Return long code.
Public Function ping(sAddress As String, Reply As ICMP_ECHO_REPLY) As Long

    Dim hIcmp As Long
    Dim lAddress As Long
    Dim lTimeOut As Long
    Dim StringToSend As String

    'Short string of data to send
    StringToSend = "hello"

    'ICMP (ping) timeout
    lTimeOut = 1000 'ms

    'Convert string address to a long representation.
    lAddress = inet_addr(sAddress)

    If (lAddress <> -1) And (lAddress <> 0) Then
       
        'Create the handle for ICMP requests.
        hIcmp = IcmpCreateFile()
   
        If hIcmp Then
            'Ping the destination IP address.
            Call IcmpSendEcho(hIcmp, lAddress, StringToSend, Len(StringToSend), 0, Reply, Len(Reply), lTimeOut)

            'Reply status
            ping = Reply.Status
       
            'Close the Icmp handle.
            IcmpCloseHandle hIcmp
        Else
            Debug.Print "failure opening icmp handle."
            ping = -1
        End If
    Else
        ping = -1
    End If

End Function

'Clean up the sockets.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Public Sub SocketsCleanup()
   
    WSACleanup
   
End Sub

'Get the sockets ready.
'http://support.microsoft.com/default.aspx?scid=kb;EN-US;q154512
Public Function SocketsInitialize() As Boolean

    Dim WSAD As WSADATA

    SocketsInitialize = WSAStartup(WS_VERSION_REQD, WSAD) = ICMP_SUCCESS

End Function

'Convert the ping response to a message that you can read easily from constants.
'For more information about these constants, visit the following Microsoft Web site:
'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pingstatus.asp

Public Function EvaluatePingResponse(PingResponse As Long) As String

    Select Case PingResponse
   
            'Success
        Case ICMP_SUCCESS: EvaluatePingResponse = "Online"
           
            'Some error occurred
        Case ICMP_STATUS_BUFFER_TO_SMALL:    EvaluatePingResponse = "Buffer Too Small"
        Case ICMP_STATUS_DESTINATION_NET_UNREACH: EvaluatePingResponse = "Destination Net Unreachable"
        Case ICMP_STATUS_DESTINATION_HOST_UNREACH: EvaluatePingResponse = "Destination Host Unreachable"
        Case ICMP_STATUS_DESTINATION_PROTOCOL_UNREACH: EvaluatePingResponse = "Destination Protocol Unreachable"
        Case ICMP_STATUS_DESTINATION_PORT_UNREACH: EvaluatePingResponse = "Destination Port Unreachable"
        Case ICMP_STATUS_NO_RESOURCE: EvaluatePingResponse = "No Resources"
        Case ICMP_STATUS_BAD_OPTION: EvaluatePingResponse = "Bad Option"
        Case ICMP_STATUS_HARDWARE_ERROR: EvaluatePingResponse = "Hardware Error"
        Case ICMP_STATUS_LARGE_PACKET: EvaluatePingResponse = "Packet Too Big"
        Case ICMP_STATUS_REQUEST_TIMED_OUT: EvaluatePingResponse = "Caido" 'Request Timed Out
        Case ICMP_STATUS_BAD_REQUEST: EvaluatePingResponse = "Bad Request"
        Case ICMP_STATUS_BAD_ROUTE: EvaluatePingResponse = "Bad Route"
        Case ICMP_STATUS_TTL_EXPIRED_TRANSIT: EvaluatePingResponse = "TimeToLive Expired Transit"
        Case ICMP_STATUS_TTL_EXPIRED_REASSEMBLY: EvaluatePingResponse = "TimeToLive Expired Reassembly"
        Case ICMP_STATUS_PARAMETER: EvaluatePingResponse = "Parameter Problem"
        Case ICMP_STATUS_SOURCE_QUENCH: EvaluatePingResponse = "Source Quench"
        Case ICMP_STATUS_OPTION_TOO_BIG: EvaluatePingResponse = "Option Too Big"
        Case ICMP_STATUS_BAD_DESTINATION: EvaluatePingResponse = "Bad Destination"
        Case ICMP_STATUS_NEGOTIATING_IPSEC: EvaluatePingResponse = "Negotiating IPSEC"
        Case ICMP_STATUS_GENERAL_FAILURE: EvaluatePingResponse = "General Failure"
           
            'Unknown error occurred
        Case Else: EvaluatePingResponse = "Unknown Response"
       
    End Select

End Function


Esto en El formulario, Particularmente en un timer con 5 segundos...
Código: [Seleccionar]
    Dim Reply As ICMP_ECHO_REPLY
    Dim lngSuccess As Long
    Dim strIPAddress As String


    If SocketsInitialize() Then
     
        strIPAddress = "8.8.8.8" > DNS DE GOOGLE generalmente usado para hacer ping, podes poner la de tu pagina web o la que vos quieras...
   
        lngSuccess = ping(strIPAddress, Reply)
     

        If EvaluatePingResponse(lngSuccess) <> "Online" Then
               
            Debug.Print "NO HAY INTERNET"
        Else
               
            Debug.Print "HAY INTERNET"
                   
        End If

        SocketsCleanup
     
    Else
   
        Debug.Print WINSOCK_ERROR
   
    End If


El resultado es instantaneo... yo lo eh probado y funciona perfecto y no tiene el problema que vos decis...

SALUDOS =)

Bazooka

  • Terabyte
  • *****
  • Mensajes: 951
  • Reputación: +31/-20
  • El pibe Bazooka
    • Ver Perfil
    • Desof sistemas
Re:Comprobar conexión a internet.
« Respuesta #27 en: Mayo 24, 2014, 08:33:32 pm »
Hola amigo estuve viendo tu video y me parece que no se liberan los recursos del objeto que creas y la mejor prueba es que al cargar el visual de nuevo anda correcto.

Dejame hacer unas pruebas y te hago el comentario mas claro
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Bazooka

  • Terabyte
  • *****
  • Mensajes: 951
  • Reputación: +31/-20
  • El pibe Bazooka
    • Ver Perfil
    • Desof sistemas
Re:Comprobar conexión a internet.
« Respuesta #28 en: Mayo 24, 2014, 08:48:58 pm »
YO lo probe exactamente como vos lo estas haciendo y me funciona correctamente de las 2 maneras dentro de la VM y fuera .
Solo que no se si lo que tu dices de desconectar el router es quitarle la alimentacion o desconectar el cable de red del mismo. (esto ultimo es lo que yo hice)

Ojala te sirva
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Bazooka

  • Terabyte
  • *****
  • Mensajes: 951
  • Reputación: +31/-20
  • El pibe Bazooka
    • Ver Perfil
    • Desof sistemas
Re:Comprobar conexión a internet.
« Respuesta #29 en: Mayo 24, 2014, 08:59:00 pm »
intenta con esto!


Código: [Seleccionar]
Option Explicit

Dim xml As Object
 
Public Function CheckConnection(sURL) As Boolean
  Dim lTime As Long
  xml.Open "GET", sURL, True
  xml.Send
 
  lTime = Timer
  Do While xml.readyState <> 4
    DoEvents
 
    If lTime + 5 < Timer Then '5 Segundos de espera
      CheckConnection = False
      Exit Function
    End If
  Loop
 
  CheckConnection = CBool(xml.Status = 0)
End Function
 
Private Sub Form_Load()
  Set xml = CreateObject("Microsoft.XMLHTTP")
 Timer1 = True
End Sub

Private Sub Form_Unload(Cancel As Integer)
Timer1 = False
Set xml = Nothing
End Sub

Private Sub Timer1_Timer()
    If CheckConnection("http://www.google.com.ar/") Then
       Label1 = "Hay Internet"
    Else
       Label1 = "No Hay Internet"
       
    End If
End Sub
 
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.