/*
* ===================================================== ========================================================== ======
*
* 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;
}