gethostbyname2_r - Linux
Overview
gethostbyname2_r
is a low-level function in the GNU C Library (glibc) that resolves a hostname to its corresponding IPv4 or IPv6 address. It performs this task in a thread-safe manner, which is particularly useful in multithreaded applications.
Syntax
int gethostbyname2_r(const char *name,
int af,
struct hostent *result_buf,
char *buf,
size_t buflen,
struct hostent **result,
int *h_errnop);
Options/Flags
- name: The hostname to resolve.
- af: The address family to resolve the hostname for. Valid values are
AF_INET
for IPv4 andAF_INET6
for IPv6. - result_buf: A pointer to a user-allocated buffer where the results of the resolution will be stored.
- buf: A pointer to a user-allocated buffer for intermediate storage.
- buflen: The size of the
buf
buffer. - result: A pointer to a variable that will receive a pointer to the
hostent
structure containing the resolution results. - h_errnop: A pointer to an integer variable that will receive an error code if the resolution fails.
Examples
Resolving an IPv4 hostname:
#include <netdb.h>
#include <stdio.h>
int main() {
struct hostent *result;
int h_errno;
char buf[4096];
result = gethostbyname2_r("example.com", AF_INET, NULL, buf, sizeof(buf), &result, &h_errno);
if (result) {
printf("IPv4 address: %s\n", result->h_addr_list[0]);
} else {
printf("Error resolving hostname: %s\n", hstrerror(h_errno));
}
return 0;
}
Resolving an IPv6 hostname:
#include <netdb.h>
#include <stdio.h>
int main() {
struct hostent *result;
int h_errno;
char buf[4096];
result = gethostbyname2_r("example.com", AF_INET6, NULL, buf, sizeof(buf), &result, &h_errno);
if (result) {
printf("IPv6 address: %s\n", result->h_addr_list[0]);
} else {
printf("Error resolving hostname: %s\n", hstrerror(h_errno));
}
return 0;
}
Common Issues
h_errno
is set toHOST_NOT_FOUND
: This indicates that the specified hostname does not exist.h_errno
is set toTRY_AGAIN
: This indicates that the DNS server is temporarily unavailable. Retry the request later.h_errno
is set toNO_RECOVERY
: This indicates that the DNS lookup failed and cannot be recovered.
Integration
gethostbyname2_r
can be used in conjunction with other networking-related commands and functions, such as getaddrinfo()
and socket()
, to establish network connections and resolve hostnames programmatically.
Related Commands
gethostbyname()
: Resolves a hostname to its corresponding IPv4 address.gethostbyname2()
: Resolves a hostname to its corresponding IPv4 or IPv6 address.getaddrinfo()
: Resolves a hostname or service name to a list of corresponding IP addresses and port numbers.