Getaddrinfo performs domain name resolution for ipv4 and ipv6

Source: Internet
Author: User

/*
* ===================================================== ========================================================== ======
*
* Filename: getaddrinfo. c
*
* Description:
*
* Version: 1.0
* Created: 05:29:51
* Revision: none
* Compiler: gcc
*
* Author: your name (),
* Company:
*
* ===================================================== ========================================================== ======
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <netdb. h>
# Include <netinet/in. h>
# Include <sys/socket. h>
 
# Ifndef NI_MAXHOST
# Deprecision NI_MAXHOST 1025
# Endif
 
Char * get_ip_str (const struct sockaddr * sa, char * s, size_t maxlen)
{
Switch (sa-> sa_family ){
Case AF_INET:
Inet_ntop (AF_INET, & (struct sockaddr_in *) sa)-> sin_addr ),
S, maxlen );
Break;

Case af_inet6:
Inet_ntop (af_inet6, & (struct sockaddr_in6 *) SA)-> sin6_addr ),
S, maxlen );
Break;

Default:
Strncpy (S, "unknown af", maxlen );
Return NULL;
}

Return s;
}

Int main (void)
{
Struct addrinfo * result;
Struct addrinfo * res;
Struct sockaddr_in * sin;
Struct sockaddr_in6 * sin6;
Char buf [128];
Int error;
 
/* Resolve the domain name into a list of addresses */
Error = getaddrinfo ("www.baidu.com", NULL, NULL, & result );
If (error! = 0)
{
Fprintf (stderr, "error in getaddrinfo: % s/n", gai_strerror (error ));
Return EXIT_FAILURE;
}
 
Printf ("get a correct result/n ");
For (res = result; res! = NULL; res = res-> ai_next)
{
Get_ip_str (res-> ai_addr, buf, 128 );
Printf ("% s/n", buf );
}

/* Loop over all returned results and do inverse lookup */
For (res = result; res! = NULL; res = res-> ai_next)
{
Char hostname [NI_MAXHOST] = "";
 
Error = getnameinfo (res-> ai_addr, res-> ai_addrlen, hostname, ni_maxhost, null, 0, 0 );
If (error! = 0)
{
Fprintf (stderr, "error in getnameinfo: % s/n", gai_strerror (error ));
Continue;
}
If (* hostname! = '/0 ')
Printf ("hostname: % s/n", hostname );
}
 
Freeaddrinfo (result );
Return exit_success;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.