getaddrinfo

From Wikipedia, the free encyclopedia

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().

[edit] Example

The following example uses getaddrinfo() to get a result, then calls getnameinfo() 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 <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
 
 
#ifndef   NI_MAXHOST
#define   NI_MAXHOST 1025
#endif // NI_MAX_HOST
 
 
int main()
{
    struct addrinfo * result;
 
    size_t hostname_len = NI_MAXHOST;
    char * hostname     = NULL;
 
    int error;
 
    if ( 0 != ( error = getaddrinfo( "www.example.com", NULL, NULL, &result ) ) )
    {
        fprintf( stderr, "error using getaddrinfo: %s\n", gai_strerror( error ) );
    }
 
    if ( result )
    {
        for( ; ; hostname_len *= 2 )
        {
            hostname = ( char * ) realloc( hostname, hostname_len );
 
            if ( NULL == hostname )
            {
                perror( "" );
                break;  
            }
 
            error = getnameinfo( result->ai_addr, result->ai_addrlen, hostname, hostname_len, NULL, 0, 0 );
 
            if ( 0 == error )
            {
                break;
            }
 
            if ( EAI_OVERFLOW != error )
            {
                fprintf( stderr, "error using getaddrinfo: %s\n", gai_strerror( error ) );
                break;
            }
        }
 
        if ( NULL != hostname )
        {
            free( hostname );
        }
 
        freeaddrinfo( result );
    }
 
    return 0;
}

[edit] See also