Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Otros temas > Trucos
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Los mejores trucos

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 15-05-2008
Avatar de escafandra
[escafandra] escafandra is offline
Miembro Premium
 
Registrado: nov 2007
Posts: 2.197
Poder: 20
escafandra Tiene un aura espectacularescafandra Tiene un aura espectacular
Hacer Ping desde código

Para hacer un Ping por código y saber si se ha tenido éxito, esta puede ser una solución.

Yo lo utilizo para comprobar que tengo conexión a internet haciendo un Ping a una página estable como google (64.233.187.99). Indudablemente puede tener muchas mas utilidades.

Esta escrito en C++. Las funciones están definidas en esta cabecera (icmpapi.h), dependiendo de vuestro compilador, es posible que dispongáis ya de la cabecera. El mio, C++Builder 5 no las tiene definidas.

Estas funciones están en la librería icmp.dll desde Windows NT y en el XP, ademas se puede acceder a ellas desde iphlpapi.dll. De forma que tendréis que preparar el compilador para que las linke.

Aquí esta la cabecera:

icmpapi.h

Código:
/*
 * Interface to the ICMP functions.
 *
 * Copyright (C) 1999 Francois Gouget
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#ifndef __WINE_ICMPAPI_H
#define __WINE_ICMPAPI_H
 
#ifdef __cplusplus
extern "C" {
#endif


HANDLE WINAPI IcmpCreateFile(
    VOID
    );

BOOL WINAPI IcmpCloseHandle(
    HANDLE  IcmpHandle
    );

DWORD WINAPI IcmpSendEcho(
    HANDLE                 IcmpHandle,
    IPAddr                 DestinationAddress,
    LPVOID                 RequestData,
    WORD                   RequestSize,
    PIP_OPTION_INFORMATION RequestOptions,
    LPVOID                 ReplyBuffer,
    DWORD                  ReplySize,
    DWORD                  Timeout
    );


#ifdef __cplusplus
}
#endif

#endif /* __WINE_ICMPAPI_H */
Y el código necesario...

Código:
//------------------------------------------------------------------------------
//  Copyright (C) Escafandra 2008
//  Hacer Ping y conocer el resultado 
//  Entrada IP en formato 255.255.255.255
//  Devuelve true si tiene exito o false si hubo un error.
//------------------------------------------------------------------------------
 
#include <winsock2.h>
#include <iphlpapi.h>
#include "icmpapi.h"


bool Ping(char* Addr)
{
    //Formato de Addr NNN.NNN.NNN.NNN

    //Declarar e inicializar variables
    bool Result = true;
    HANDLE hIcmpFile;
    unsigned long ipaddr = INADDR_NONE;
    DWORD dwRetVal = 0;
    char SendData[] = "Data Buffer";
    LPVOID ReplyBuffer = NULL;
    DWORD ReplySize = 0;

    //Obtener IP
    ipaddr = inet_addr(Addr);
    if (ipaddr == INADDR_NONE){
      Result = false;
      return Result;
    }

    hIcmpFile = IcmpCreateFile();
    if (hIcmpFile == INVALID_HANDLE_VALUE) {
      Result = false;
      return Result;
    }
    ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
    ReplyBuffer = (VOID*) malloc(ReplySize);
    if (ReplyBuffer == NULL) {
      Result = false;   // No localizacion de memoria...
      return Result;
    }

    // Envia Ping
    dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData),
        NULL, ReplyBuffer, ReplySize, 1000);

    if (dwRetVal != 0) {
        PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
        // Detectar Error en Ping (IP_STATUS)
        // ICMP_ECHO_REPLY Structure IP_STATUS code
        // http://msdn2.microsoft.com/en-us/library/aa366053(VS.85).aspx
        if(pEchoReply->Status != 0){
            Result = false;   // Error en Ping el Host no lo recibe....
        }
    }else{
      Result = false;   // Error en IcmpSendEcho localizar con GetLastError()
    }
    
    free(ReplyBuffer);
    return Result;
}
Que le saquéis partido.
Saludos.


EDITO:
Modifico el truco para repetir el ping de forma automática un número de veces pasado como parámetro. En ocasiones un sólo ping no tiene éxito...
Código:
//------------------------------------------------------------------------------
//  Copyright (C) Escafandra 2008
//  Hacer Ping y conocer el resultado
//  Entrada IP en formato 255.255.255.255
//  Devuelve true si tiene exito o false si hubo un error.
//------------------------------------------------------------------------------
#include <winsock2.h>
#include <iphlpapi.h>
#include "icmpapi.h"


bool Ping(char* Addr, int NVeces)
{
    //Formato de Addr NNN.NNN.NNN.NNN

    //Declarar e inicializar variables
    bool Result = true;
    HANDLE hIcmpFile;
    unsigned long ipaddr = INADDR_NONE;
    DWORD dwRetVal = 0;
    char SendData[] = "Data Buffer";
    LPVOID ReplyBuffer = NULL;
    DWORD ReplySize = 0;

    //Obtener IP de Addr
    ipaddr = inet_addr(Addr);
    if (ipaddr == INADDR_NONE){
      Result = false;
      return Result;
    }

    hIcmpFile = IcmpCreateFile();
    if (hIcmpFile == INVALID_HANDLE_VALUE) {
      Result = false;
      return Result;
    }
    ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
    ReplyBuffer = (VOID*) malloc(ReplySize);
    if (ReplyBuffer == NULL) {
      Result = false;   // No localizacion de memoria...
      return Result;
    }

    // Envia Ping
    Result = true;
    for(int n=0; n<NVeces>ProcessMessages();
      dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData),
           NULL, ReplyBuffer, ReplySize, 1000);

      if (dwRetVal != 0) {
         PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
         // Detectar Error en Ping (IP_STATUS)
         // ICMP_ECHO_REPLY Structure IP_STATUS code
         // http://msdn2.microsoft.com/en-us/library/aa366053(VS.85).aspx
         if(pEchoReply->Status != 0){
            Result = false;   // Error en Ping el Host no lo recibe....
         }
      }else{
         Result = false;   // Error en IcmpSendEcho localizar con GetLastError()
      }
      if(Result) break;
      Sleep(1000);
    }

    free(ReplyBuffer);
    return Result;
}
Saludos.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro


La franja horaria es GMT +2. Ahora son las 22:37:15.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi