Tuesday 21 August 2012

IPV6 Hostname Resolution in Linx

/* IPV6 resolving host name
arg: hostname*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main (int argc, char *argv[])
{
                struct addrinfo *res;
                char ip_addr[INET6_ADDRSTRLEN];
                struct sockaddr_in6 *saddr;
                socklen_t       len ;

                saddr = NULL;

                if( argc != 2 )
                {
                                return -1;
                }

                res = NULL;

                printf("host[%s]\n", argv[1]);

                getaddrinfo(argv[1], NULL ,NULL,&res);

                if ( res != NULL )
                {
                                printf("ai_flags -> %i\n", res->ai_flags) ;
                                printf("ai_family -> %i\n", res->ai_family) ;
                                printf("ai_socktype -> %i\n", res->ai_socktype) ;
                                printf("ai_protocol -> %i\n", res->ai_protocol) ;
                                printf("ai_addrlen -> %i\n", res->ai_addrlen) ;

                                if ( res->ai_family == 2 )
                                {
                                        struct sockaddr_in *saddr = (struct sockaddr_in*)res->ai_addr;
                                        printf("ai_addr hostname ->  %s\n", inet_ntoa( saddr->sin_addr));
                                   }

                                if ( res->ai_family == 10 )
                                {
                                        saddr = (struct sockaddr_in6*)res->ai_addr;

                                        inet_ntop(AF_INET6, &saddr->sin6_addr, ip_addr, INET6_ADDRSTRLEN);
                                    printf("address[%s]\n", ip_addr);
                                 }
                }
                else
                {
                                printf("host is not found\n");
                }

                freeaddrinfo(res);

                return 0 ;
}

No comments:

Post a Comment