hostent Structure (Windows Sockets)

The hostent structure contains information about a host, including its name and a list of its IP addresses. This structure is returned by the gethostbyname and gethostbyaddr functions.

Structure Definition


struct hostent {
    char FAR * h_name;          // Official name of the host.
    char FAR ** h_aliases;       // A NULL-terminated array of alternate names for the host.
    int h_addrtype;             // The type of addresses returned. For the Windows Sockets API, this will always be AF_INET.
    int h_length;               // The length, in bytes, of each address in the h_addr_list array.
    char FAR ** h_addr_list;     // A NULL-terminated array of network addresses for the host, in network byte order.
};
            

Members

Usage Example (Conceptual)

Using gethostbyname


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

// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct hostent *remoteHost;
    char *ipAddress;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        std::cerr << "WSAStartup failed: " << iResult << std::endl;
        return 1;
    }

    // Resolve the hostname
    remoteHost = gethostbyname("www.example.com");

    if (remoteHost == NULL) {
        std::cerr << "gethostbyname failed with error: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    std::cout << "Official name: " << remoteHost->h_name << std::endl;

    std::cout << "Aliases:" << std::endl;
    for (char **alias = remoteHost->h_aliases; *alias != 0; alias++) {
        std::cout << "  " << *alias << std::endl;
    }

    if (remoteHost->h_addrtype == AF_INET) {
        std::cout << "Address Type: AF_INET (IPv4)" << std::endl;
        std::cout << "Addresses:" << std::endl;
        for (char **ptr = remoteHost->h_addr_list; *ptr != 0; ptr++) {
            ipAddress = inet_ntoa (*(struct in_addr *)*ptr);
            std::cout << "  " << ipAddress << std::endl;
        }
    } else {
        std::cerr << "Unsupported address type." << std::endl;
    }

    WSACleanup();
    return 0;
}
            

Related Functions