Estructura HOSTENT (winsock.h)

Las funciones usan la estructura de host para almacenar información sobre un host determinado, como el nombre de host, la dirección IPv4, etc. Una aplicación nunca debe intentar modificar esta estructura o liberar cualquiera de sus componentes. Además, solo se asigna una copia de la estructura hostent por subproceso y, por tanto, una aplicación debe copiar cualquier información que necesite antes de emitir cualquier otra llamada API de Windows Sockets.

Sintaxis

typedef struct hostent {
  char  *h_name;
  char  **h_aliases;
  short h_addrtype;
  short h_length;
  char  **h_addr_list;
} HOSTENT, *PHOSTENT, *LPHOSTENT;

Miembros

h_name

Nombre oficial del host (PC). Si usa el DNS o un sistema de resolución similar, es el nombre de dominio completo (FQDN) que provocó que el servidor devolva una respuesta. Si usa un archivo de hosts local, es la primera entrada después de la dirección IPv4.

h_aliases

Matriz terminada en NULL de nombres alternativos.

h_addrtype

Tipo de dirección que se va a devolver.

h_length

Longitud, en bytes, de cada dirección.

h_addr_list

Una lista terminada en NULL de direcciones para el host. Las direcciones se devuelven en orden de bytes de red. La macro h_addr se define para que sea h_addr_list[0] compatible con software anterior.

Comentarios

Las funciones gethostbyaddr y gethostbyname devuelven un puntero a una estructura de host , una estructura asignada por Windows Sockets. La estructura de host contiene los resultados de una búsqueda correcta del host especificado en el parámetro name .

El archivo DLL de Winsock asigna internamente la memoria de la estructura hostent devuelta por las funciones gethostbydr y gethostbyname desde el almacenamiento local del subproceso. Solo se asigna y usa una única estructura de host , independientemente de cuántas veces se llamen a las funciones gethostbyaddr o gethostbyname en el subproceso. La estructura de host devuelta debe copiarse en un búfer de aplicación si se deben realizar llamadas adicionales a las funciones gethostbyaddr o gethostbyname en el mismo subproceso. De lo contrario, las llamadas gethostbyaddr o gethostbyname posteriores sobrescribirán el valor devuelto en el mismo subproceso. El archivo DLL winsock libera la memoria interna asignada para la estructura de host devuelta cuando se cierra el subproceso.

Una aplicación no debe intentar liberar la memoria usada por la estructura de host devuelta. La aplicación nunca debe intentar modificar esta estructura o liberar cualquiera de sus componentes. Además, solo se asigna una copia de esta estructura por subproceso, por lo que la aplicación debe copiar cualquier información que necesite antes de emitir otras llamadas de función a gethostbyaddr o gethostbyname.

Ejemplos

En los ejemplos siguientes se muestra el uso de la estructura hostent con la función gethostbyname .

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")

int main(int argc, char **argv)
{

    //-----------------------------------------
    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;

    DWORD dwError;
    int i = 0;

    struct hostent *remoteHost;
    char *host_name;
    struct in_addr addr;

    char **pAlias;

    // Validate the parameters
    if (argc != 2) {
        printf("usage: %s ipv4address\n", argv[0]);
        printf(" or\n");
        printf("       %s hostname\n", argv[0]);
        printf("  to return the host\n");
        printf("       %s 127.0.0.1\n", argv[0]);
        printf("  to return the IP addresses for a host\n");
        printf("       %s www.contoso.com\n", argv[0]);
        return 1;
    }
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    host_name = argv[1];

// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
    if (isalpha(host_name[0])) {        /* host address is a name */
        printf("Calling gethostbyname with %s\n", host_name);
        remoteHost = gethostbyname(host_name);
    } else {
        printf("Calling gethostbyaddr with %s\n", host_name);
        addr.s_addr = inet_addr(host_name);
        if (addr.s_addr == INADDR_NONE) {
            printf("The IPv4 address entered must be a legal address\n");
            return 1;
        } else
            remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
    }

    if (remoteHost == NULL) {
        dwError = WSAGetLastError();
        if (dwError != 0) {
            if (dwError == WSAHOST_NOT_FOUND) {
                printf("Host not found\n");
                return 1;
            } else if (dwError == WSANO_DATA) {
                printf("No data record found\n");
                return 1;
            } else {
                printf("Function failed with error: %ld\n", dwError);
                return 1;
            }
        }
    } else {
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
            printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
        }
        printf("\tAddress type: ");
        switch (remoteHost->h_addrtype) {
        case AF_INET:
            printf("AF_INET\n");
            break;
        case AF_INET6:
            printf("AF_INET6\n");
            break;
        case AF_NETBIOS:
            printf("AF_NETBIOS\n");
            break;
        default:
            printf(" %d\n", remoteHost->h_addrtype);
            break;
        }
        printf("\tAddress length: %d\n", remoteHost->h_length);

        if (remoteHost->h_addrtype == AF_INET) {
            while (remoteHost->h_addr_list[i] != 0) {
                addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
                printf("\tIPv4 Address #%d: %s\n", i, inet_ntoa(addr));
            }
        } else if (remoteHost->h_addrtype == AF_INET6)
            printf("\tRemotehost is an IPv6 address\n");
    }

    return 0;
}

Requisitos

Requisito Value
Cliente mínimo compatible Windows 2000 Professional [solo aplicaciones de escritorio]
Servidor mínimo compatible Windows 2000 Server [solo aplicaciones de escritorio]
Encabezado winsock.h (incluya Winsock2.h)

Consulte también

GetAddrInfoEx

GetAddrInfoW

addrinfo

addrinfoW

getaddrinfo

gethostbyaddr

gethostbyname