gethostbyname Function
The gethostbyname function retrieves host information, given the host's name.
struct hostent* FAR PASCAL gethostbyname(const char FAR* name);
Parameters
| Parameter | Description |
|---|---|
name |
Pointer to a null-terminated ASCII string that contains the name of the host for which to retrieve information. |
Return Value
If the function succeeds, the return value is a pointer to a hostent structure. If the function fails, the return value is NULL. If a NULL is returned, a specific error code can be retrieved by calling WSAGetLastError.
| Return Type | Description |
|---|---|
hostent* |
Pointer to a hostent structure that contains information about the specified host.
|
Remarks
The gethostbyname function retrieves the host name, its alias list, and the list of IP addresses associated with the host from the database. The hostent structure is defined in the Winsock2.h header file.
The hostent structure contains:
char *h_name: The official name of the host.char **h_aliases: A null-terminated array of alternative names for the host (aliases).int h_addrtype: The type of the address returned. For the Internet Protocol version, this value is AF_INET.int h_length: The length, in bytes, of the address.char **h_addr_list: A null-terminated array of network addresses for the host, in network byte order.
The gethostbyname function is a protocol-independent name resolution function. The AF_INET address family is supported. Support for other address families is dependent on the underlying name resolution service.
Note: For new applications, it is recommended to use the
getaddrinfo and freeaddrinfo functions for name resolution. These functions provide support for both IPv4 and IPv6, and offer greater flexibility.
Example Usage
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
struct hostent *host_info;
char *hostname = "www.example.com";
char ip_address[INET_ADDRSTRLEN];
// Initialize Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed.\n");
return 1;
}
// Get host information
host_info = gethostbyname(hostname);
if (host_info == NULL) {
fprintf(stderr, "gethostbyname failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Display host information
printf("Official Name: %s\n", host_info->h_name);
if (host_info->h_aliases[0] != NULL) {
printf("Aliases:\n");
for (char **alias = host_info->h_aliases; *alias != NULL; alias++) {
printf(" - %s\n", *alias);
}
}
if (host_info->h_addrtype == AF_INET) {
printf("IP Addresses:\n");
for (char **addr = host_info->h_addr_list; *addr != NULL; addr++) {
struct in_addr addr_list;
memcpy(&addr_list, *addr, sizeof(struct in_addr));
printf(" - %s\n", inet_ntoa(addr_list));
}
} else {
printf("Address type is not AF_INET.\n");
}
// Clean up Winsock
WSACleanup();
return 0;
}