/* addrinfo_ntop.c by vinco at 2012-05-18
* i386-Red Hat-gcc-4.1.2
* http://blog.csdn.net/xuyunzhang/
* Copyright: All Reserved
*/
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int addrinfo(char* host, char *serv);
int addrinfo_ntop(const struct addrinfo *paddrinfo,
char *host, size_t hostlen,
char *serv, size_t servlen);
int main()
{
char host[64]="member.qq.com", serv[64]="8000";
//char host[64]="183.60.49.253", serv[64]="8000";
addrinfo( host, serv);
}
int addrinfo(char* host, char *serv)
{
struct addrinfo hints, *res = NULL, *paddrinfo = NULL;
char hostname[64]={0}, servname[64]={0};
int ret = -1;
if( !host || !serv )
return -1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* AF_INET6 or AF_INET */
hints.ai_socktype = SOCK_DGRAM;
//hints.ai_flags = ;
if( (ret = getaddrinfo( host, serv, &hints, &res)) )
{
printf("getaddrinfo error:%s\n", gai_strerror(ret) );
return -1;
}
for(paddrinfo = res; paddrinfo; paddrinfo = paddrinfo->ai_next )
{
if( addrinfo_ntop(paddrinfo,
hostname, sizeof(hostname),
servname, sizeof(servname)) == 0 )
{
ret = 0;
fprintf(stderr, "addrinfo_ntop host/port = %s/%s\t", hostname, servname);
}
if( getnameinfo(paddrinfo->ai_addr, paddrinfo->ai_addrlen,
hostname, sizeof(hostname),
servname, sizeof(servname),
/*NI_NUMERICHOST | NI_NUMERICSERV*/ 0) == 0 )
{
ret = 0;
fprintf(stderr, "getnameinfo host/port = %s/%s\n", hostname, servname);
}
}
putchar('\n');
freeaddrinfo(res);
return ret;
}
int addrinfo_ntop(const struct addrinfo *paddrinfo,
char *host, size_t hostlen,
char *serv, size_t servlen)
{
struct sockaddr_in *sain = NULL;
struct sockaddr_in6 *sain6 = NULL;
if( !paddrinfo || !host || !serv )
return -1;
switch ( paddrinfo->ai_family)
{
case AF_INET:
{
sain = (struct sockaddr_in *)(paddrinfo->ai_addr);
inet_ntop( paddrinfo->ai_family, &(sain->sin_addr), host, hostlen);
snprintf( serv, servlen, "%d", ntohs(sain->sin_port) );
return 0;
}
break;
case AF_INET6:
{
sain6 = (struct sockaddr_in6 *)(paddrinfo->ai_addr);
inet_ntop( paddrinfo->ai_family, &(sain6->sin6_addr), host, hostlen);
snprintf( serv, servlen, "%d", ntohs(sain6->sin6_port) );
return 0;
};
break;
default:
{
return -1;
break;
}
}
}
run && stdout
[root@localhost ctest]#
[root@localhost ctest]# gcc addrinfo_ntop.c -o addrinfo_ntop
[root@localhost ctest]#
[root@localhost ctest]#
[root@localhost ctest]# ./addrinfo_ntop
addrinfo_ntop host/port = 58.251.150.157/8000 getnameinfo host/port = reverse.gdsz.cncnet.net/irdmi
addrinfo_ntop host/port = 112.90.143.245/8000 getnameinfo host/port = 112.90.143.245/irdmi
[root@localhost ctest]#