getaddrinfo函数ipv6的应用

1..通过域名转换为点分十进制ipv6地址

addrinfo转换为sockaddr_in6

2.程序

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, char **argv)
{
	if (argc != 2) 
	{
		fprintf(stderr, "Usage: %s hostname\n",
			argv[1]);
		exit(1);   
	}


	char ipstr2[128]; 
	struct sockaddr_in6 *sockaddr_ipv6; 

	struct addrinfo *answer, hint, *curr;
	char ipstr[16];   
	bzero(&hint, sizeof(hint));
	hint.ai_family = AF_INET6;
	hint.ai_socktype = SOCK_STREAM;

	int ret = getaddrinfo(argv[1], NULL, &hint, &answer);
	if (ret != 0) 
	{
		fprintf(stderr,"getaddrinfo: &s\n",
			gai_strerror(ret));
		exit(1);
	}

	for (curr = answer; curr != NULL; curr = curr->ai_next) 
	{
		sockaddr_ipv6 = reinterpret_cast( curr->ai_addr); 
		inet_ntop(AF_INET6, &sockaddr_ipv6->sin6_addr, ipstr2,sizeof(ipstr2)); 

		//inet_ntop(AF_INET,&(((struct sockaddr_in *)(curr->ai_addr))->sin_addr),ipstr, 16);
		printf("%s\n", ipstr2);
		fflush(NULL);
	}

	freeaddrinfo(answer);
	exit(0);
}
3.运行

./a.out   域名或ipv6地址


参考地址

http://www.ibm.com/developerworks/cn/linux/l-cn-ipv4v6-sockapp/


你可能感兴趣的:(c++,Linux)