Getaddrinfo || error
Published August 21st, 2008 in Uncategorized
The getaddrinfo() function is part of the POSIX standard API in support for using it as a function to resolve a DNS hostname and IP addresses from their human-readable text form into a format for the operating system’s networking API.
The reverse function is getnameinfo().
Example
The following example uses getaddrinfo() to get a result, then calls getnameinfo()<tt> to get the canonical name for the address. Normally, this will give back the original hostname, unless the particular address has multiple names, in which case the “canonical” name is returned.
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
int main()
{
struct addrinfo *result;
char hostname[NI_MAXHOST];
int error;
if (error = getaddrinfo("www.example.com", NULL, NULL, &result))
{
fprintf(stderr, "error using getaddrinfo: %s\n", gai_strerror(error));
}
if (result)
{
if (error = getnameinfo(result->ai_addr, sizeof(struct sockaddr), hostname, sizeof(hostname), NULL,0,0))
{
fprintf(stderr, "error using getnameinfo: %s\n", gai_strerror(error));
}
}
}
See also
- Hostname
- Network address
- Domain name system