《UNIX网络编程01》 第十一章 高级名字与地址转换 getaddrinfo

getaddrinfo、gai_strerror、freeaddrinfo

#include<unistd.h>
#include<netdb.h>
#include<sys/utsname.h>

int main()
{
	struct addrinfo hints,*res;
	bzero(&hints,sizeof(hints));

	struct utsname Name;
	uname(&Name);
	int nRet = getaddrinfo(Name.nodename,"ftp",&hints,&res);

	//int nRet = getaddrinfo("127.0.0.1","23",&hints,&res);
	if(0 != nRet)
	{
		printf("error:%s\n",(char*)gai_strerror(nRet));
	}
	else
	{
		struct addrinfo *tmp = res;
		for(; NULL != tmp; tmp=tmp->ai_next)
		{
			struct sockaddr_in *pAddr;
			pAddr = (struct sockaddr_in *)tmp->ai_addr;
			printf("port:%d\n",ntohs(pAddr->sin_port));

			printf("ai_addrlen:%d\n",tmp->ai_addrlen);
			printf("ai_canonname:%s\n",tmp->ai_canonname);
			printf("ai_family:%d\n",tmp->ai_family);
			printf("ai_flags:%d\n",tmp->ai_flags);
			printf("ai_protocol:%d\n",tmp->ai_protocol);
			printf("ai_socktype:%d\n\n",tmp->ai_socktype);
		}

		freeaddrinfo(res);
	}

	return 0;
}




   

你可能感兴趣的:(《UNIX网络编程01》 第十一章 高级名字与地址转换 getaddrinfo)