FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin para Harbour/xHarbour Function HB_PING
Posts: 1710
Joined: Tue Oct 28, 2008 06:26 PM
Function HB_PING
Posted: Thu Dec 25, 2025 12:58 PM

Estimado Antonio

Es posible incluir la funci贸n HB_PING en las LIBs de la nueva versi贸n de FWH

HB_PING.PRG

#pragma BEGINDUMP
#include <hbapi.h> 
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>

int hb_Ping( const char * cp )
{
    HANDLE hIcmpFile;
    unsigned long ipaddr;
    DWORD dwRetVal;
    char SendData[32] = "Data Buffer";
    LPVOID ReplyBuffer;
    DWORD ReplySize;

ipaddr = inet_addr( cp );
if (ipaddr == INADDR_NONE)
    return 1;

hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE)
    return 2;

ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
ReplyBuffer = (VOID*) malloc(ReplySize);
if (ReplyBuffer == NULL)
    return 3;

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

if (dwRetVal == 0)
    return 4;

return 0;
}

HB_FUNC( HB_PING )
{
   hb_retni( hb_Ping( hb_parc( 1 ) ) );
}
#pragma ENDDUMP

Muchas gracias de antemano

Saludos,



Adhemar C.
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Function HB_PING
Posted: Thu Dec 25, 2025 07:27 PM

Estimado Adhemar,

Funci贸n a帽adida a FWH, muchas gracias :wink: :!:

* New: function HB_PING( cIP ) --> nResult. Ejemplo de uso:

FUNCTION Main()
    LOCAL nResultado
    LOCAL cIP := "8.8.8.8" // Servidor DNS de Google

// Llamada correcta
nResultado := HB_PING( cIP )

IF nResultado == 0
   ? "Ping exitoso a " + cIP
ELSE
   ? "Error al hacer ping. C贸digo:", nResultado
ENDIF
  RETURN NIL

Valor Significado Causa en el c贸digo C
0 Exito El ping respondi贸 correctamente (dwRetVal != 0).
1 Error de IP El formato de la IP es inv谩lido o se pas贸 un nombre de dominio (inet_addr fall贸).
2 Error de Handle No se pudo abrir el archivo ICMP (IcmpCreateFile fall贸).
3 Error de Memoria No se pudo asignar memoria para la respuesta (malloc fall贸).
4 Fallo / Timeout Se envi贸 el ping pero no hubo respuesta o hubo error en el env铆o (dwRetVal == 0).

Gracias a Adhemar Cuellar: https://forums.fivetechsupport.com/viewtopic.php?p=283090#p283090

regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 1772
Joined: Thu Sep 05, 2019 05:32 AM
Re: Function HB_PING
Posted: Thu Dec 25, 2025 08:14 PM

hi,

i have try it and got

HB_PING.prg(33): warning C4996: 'inet_addr': Use inet_pton() or InetPton() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API warnings

  • Application successfully built *

App was build and run, but how to fix the Warning ?

greeting,

Jimmy
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Function HB_PING
Posted: Fri Dec 26, 2025 05:25 AM

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <hbapi.h> #include <winsock2.h> #include <iphlpapi.h> #include <icmpapi.h>

regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Function HB_PING
Posted: Fri Dec 26, 2025 05:52 AM

Modificamos la funci贸n para que acepte dominios que se convierten a IPs:

#pragma BEGINDUMP
#include <hbapi.h> 
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>

// Nota: Aseg煤rate de enlazar con las librer铆as: ws2_32.lib e iphlpapi.lib

int hb_Ping( const char * cp )
{
    HANDLE hIcmpFile;
    unsigned long ipaddr;
    DWORD dwRetVal;
    char SendData[32] = "Data Buffer";
    LPVOID ReplyBuffer;
    DWORD ReplySize;
    

// Estructuras para manejo de DNS
WSADATA wsaData;
struct hostent *host;

// 1. Inicializar Winsock (Requerido para gethostbyname)
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    return 5; // Error: No se pudo iniciar Winsock

// 2. Intentar convertir cadena IP num茅rica directa
ipaddr = inet_addr( cp );

// 3. Si no es num茅rica, intentar resolver como dominio (DNS)
if (ipaddr == INADDR_NONE)
{
    host = gethostbyname( cp );
    if ( host == NULL )
    {
        WSACleanup();
        return 1; // Error: Nombre de dominio no v谩lido o no encontrado
    }
    ipaddr = *(unsigned long *) host->h_addr_list[0];
}

hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE)
{
    WSACleanup();
    return 2;
}

ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
ReplyBuffer = (VOID*) malloc(ReplySize);
if (ReplyBuffer == NULL)
{
    IcmpCloseHandle(hIcmpFile); // Cerrar handle antes de salir
    WSACleanup();
    return 3;
}

dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), 
    NULL, ReplyBuffer, ReplySize, 1000); // 1000ms de timeout

// Limpieza de recursos
free(ReplyBuffer);
IcmpCloseHandle(hIcmpFile);
WSACleanup();

if (dwRetVal == 0)
    return 4; // Ping fallido (Timeout o red inalcanzable)

return 0; // 脡xito
}

HB_FUNC( HB_PING )
{
   hb_retni( hb_Ping( hb_parc( 1 ) ) );
}
#pragma ENDDUMP

Cambios Clave Realizados
WSAStartup: Para usar funciones de DNS (nombres de dominio), Windows requiere que se inicie el subsistema de sockets primero. Si esto falla, devuelve el nuevo error 5.

gethostbyname: Si inet_addr dice que no es una IP num茅rica (ej. recibes "microsoft.com"), el c贸digo ahora entra en el if y pregunta al sistema por la IP de ese nombre.

WSACleanup: Es muy importante liberar los recursos de sockets antes de que la funci贸n termine (he agregado estas llamadas antes de cada return).

Limpieza de Memoria: Agregu茅 free(ReplyBuffer) y IcmpCloseHandle antes de salir para evitar fugas de memoria si usas esta funci贸n muchas veces seguidas.

// 1. Funciona con IPs
nRes := HB_PING( "8.8.8.8" ) 

// 2. Funciona con Dominios
nRes := HB_PING( "google.com" )
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 1710
Joined: Tue Oct 28, 2008 06:26 PM
Re: Function HB_PING
Posted: Fri Dec 26, 2025 11:13 AM

Excelente

Muchas gracias Estimado Antonio

Saludos,



Adhemar C.

Continue the discussion