Condividi tramite


Funzione gethostbyaddr (winsock2.h)

[gethostbyaddr non è più consigliato per l'uso a partire da Windows Sockets 2. Usare invece getnameinfo.]

La funzione gethostbyaddr recupera le informazioni sull'host corrispondenti a un indirizzo di rete.

Sintassi

hostent *WSAAPI gethostbyaddr(
  const char *addr,
  int        len,
  int        type
);

Parametri

addr

TBD

len

TBD

type

TBD

Valore restituito

Se non si verifica alcun errore, gethostbyaddr restituisce un puntatore alla struttura hostent . In caso contrario, restituisce un puntatore Null e un codice di errore specifico può essere recuperato chiamando WSAGetLastError.

Codice di errore Significato
WSANOTINITIALISED
Prima di usare questa funzione, è necessario che venga eseguita una chiamata WSAStartup riuscita.
WSAEINVAL
Argomento fornito non valido. Questo errore viene restituito se AF_INET6 è stato specificato nel parametro di tipo e il parametro len non è stato impostato uguale alle dimensioni di un indirizzo IPv6.
WSAENETDOWN
Il sottosistema di rete non è riuscito.
WSAHOST_NOT_FOUND
Host di risposte autorevole non trovato.
WSATRY_AGAIN
Host non autenticativo non trovato o server non riuscito.
WSANO_RECOVERY
Si è verificato un errore irreversibile.
WSANO_DATA
Nome valido, nessun record di dati di tipo richiesto.
WSAEINPROGRESS
È in corso una chiamata di Windows Sockets 1.1 bloccante oppure il provider di servizi sta ancora elaborando una funzione di callback.
WSAEAFNOSUPPORT
Il tipo specificato non è supportato dall'implementazione di Windows Sockets.
WSAEFAULT
Il parametro addr non è una parte valida dello spazio indirizzi utente o il parametro len è troppo piccolo.
WSAEINTR
Una chiamata di Windows Socket 1.1 bloccata è stata annullata tramite WSACancelBlockingCall.

Commenti

La funzione gethostbyaddr restituisce un puntatore alla struttura hostent contenente il nome e l'indirizzo corrispondenti all'indirizzo di rete specificato.

La memoria per la struttura hostent restituita dalla funzione gethostbyaddr viene allocata internamente dalla DLL Winsock dall'archiviazione locale del thread. Solo una singola struttura hostent viene allocata e usata, indipendentemente dal numero di volte in cui vengono chiamate le funzioni gethostbyaddr o gethostbyname nel thread. La struttura hostent restituita deve essere copiata in un buffer dell'applicazione se devono essere effettuate chiamate aggiuntive alle funzioni gethostbyaddr o gethostbyname nello stesso thread. In caso contrario, il valore restituito verrà sovrascritto dalle successive chiamate gethostbyaddr o gethostbyname sullo stesso thread. La memoria interna allocata per la struttura hostent restituita viene rilasciata dalla DLL Winsock quando il thread viene chiuso.

Un'applicazione non deve provare a rilasciare la memoria usata dalla struttura hostent restituita. L'applicazione non deve mai tentare di modificare questa struttura o di liberare i relativi componenti. Inoltre, viene allocata una sola copia di questa struttura per ogni thread, quindi l'applicazione deve copiare tutte le informazioni necessarie prima di eseguire qualsiasi altra chiamata di funzione per gethostbyaddr o gethostbyname.

Anche se gethostbyaddr non è più consigliato per l'uso a partire da Windows Sockets 2 e deve essere usata la funzione getnameinfo , gethostbyaddr è in grado di restituire un nome NetBIOS; getnameinfo non è . Gli sviluppatori che richiedono la risoluzione dei nomi NetBIOS potrebbero dover usare gethostbyaddr fino a quando le applicazioni non sono completamente indipendenti dai nomi NetBIOS.

Nota La possibilità di eseguire ricerche inversa usando la funzione gethostbyaddr è utile, ma tali ricerche sono considerate intrinsecamente inaffidabili e devono essere usate solo come hint.
 

Codice di esempio

Nell'esempio seguente viene illustrato l'uso della funzione gethostbyaddr .
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

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

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

    DWORD dwError;
    int i = 0;
    int bIpv6 = 0;

    struct hostent *remoteHost;
    char *host_addr;
    struct in_addr addr = { 0 };
    IN6_ADDR addr6;

    char **pAlias;

    // Validate the parameters
    if (argc < 2) {
        printf("usage: %s 4 ipv4address\n", argv[0]);
        printf(" or\n");
        printf("usage: %s 6 ipv6address\n", argv[0]);
        printf("  to return the hostname\n");
        printf("       %s 4 127.0.0.1\n", argv[0]);
        printf("       %s 6 0::1\n", argv[0]);
        return 1;
    }
    // Validate parameters 
    if (atoi(argv[1]) == 4)
        bIpv6 = 0;
    else if (atoi(argv[1]) == 6)
        bIpv6 = 1;
    else {
        printf("usage: %s 4 ipv4address\n", argv[0]);
        printf(" or\n");
        printf("usage: %s 6 ipv6address\n", argv[0]);
        printf("  to return the hostname\n");
        printf("       %s 4 127.0.0.1\n", argv[0]);
        printf("       %s 6 0::1\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_addr = argv[2];

    printf("Calling gethostbyaddr with %s\n", host_addr);
    if (bIpv6 == 1) {
        {
            iResult = inet_pton(AF_INET6, host_addr, &addr6);
            if (iResult == 0) {
                printf("The IPv6 address entered must be a legal address\n");
                return 1;
            } else
                remoteHost = gethostbyaddr((char *) &addr6, 16, AF_INET6);
        }
    } else {
        addr.s_addr = inet_addr(host_addr);
        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;
}

Windows Phone 8: questa funzione è supportata per le app dello Store di Windows Phone in Windows Phone 8 e versioni successive.

Windows 8.1 e Windows Server 2012 R2: questa funzione è supportata per le app di Windows Store in Windows 8.1, Windows Server 2012 R2 e versioni successive.

Requisiti

Requisito Valore
Client minimo supportato Windows 8.1, Windows Vista [app desktop | App UWP]
Server minimo supportato Windows Server 2003 [app desktop | App UWP]
Piattaforma di destinazione Windows
Intestazione winsock2.h (include Winsock2.h, Winsock.h)
Libreria Ws2_32.lib
DLL Ws2_32.dll

Vedi anche

GetAddrInfoEx

GetAddrInfoW

WSAAsyncGetHostByAddr

Funzioni Winsock

Informazioni di riferimento su Winsock

addrinfo

addrinfoW

getaddrinfo

gethostbyname

hostent