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.
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.
};
char FAR * h_name:
This member points to the official name of the host.
char FAR ** h_aliases:
This member points to a NULL-terminated array of pointers to strings. Each string is an alternate name for the host. The original name in h_name is also included in this list.
int h_addrtype:
This member indicates the type of addresses returned by the functions. For the Windows Sockets API, this member will always be AF_INET, indicating that the addresses are IPv4 addresses.
int h_length:
This member specifies the length, in bytes, of each network address stored in the h_addr_list array. For IPv4 addresses, this is typically 4 bytes.
char FAR ** h_addr_list:
This member points to a NULL-terminated array of pointers. Each pointer in the array points to a network address for the host. The addresses are stored in network byte order.
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;
}