getaddrinfo函数在Winsock中的使用方法

#include 
#include 
#include 
#include 
#pragma comment(lib,"ws2_32.lib")

int _tmain()
{
	//加载WinSock库
	int nRet = 0;
	WSADATA wd;
	nRet = WSAStartup(MAKEWORD(2, 2), &wd);
	if (nRet != 0)
	{
		_tprintf(_T("加载WinSock库失败,错误码为:%d\n"), nRet);
		_gettchar();
		return 0;
	}

	char hostName[256] = {0};
	//此函数获取本地主机名
	if (gethostname(hostName, 256) != 0)
	{
		_tprintf(_T("获取主机名失败,错误码为:%d\n"), WSAGetLastError());
		goto UNLOAD;
	}
	else
		printf("主机名:%s\n",hostName);

	struct addrinfo aiHints;
	ZeroMemory(&aiHints, sizeof(aiHints));
	aiHints.ai_family = AF_INET;

	struct addrinfo *pAiLinkedList = NULL;//指向链表的指针必须初始化为NULL
	//此函数提供了与协议无关的通过主机名获取地址信息的方法
	nRet=getaddrinfo(
		hostName,//主机名或点分十进制格式的IP地址
		NULL,
		&aiHints,
		&pAiLinkedList//指向由多个addrinfo结构组成的链表
		);
	if (nRet != 0)
		_tprintf(_T("获取地址信息失败,错误码为:%d\n"), nRet);
	else
	{
		struct addrinfo *pAi;
		printf("本机的IPv4地址如下:\n");
		for (pAi = pAiLinkedList; pAi != NULL; pAi = pAi->ai_next)
		{
			struct sockaddr_in* pAddr = pAi->ai_addr;
			char* pszIp = inet_ntoa(pAddr->sin_addr);
			printf("\t%s\n",pszIp);
		}
	}

UNLOAD:
	//释放WinSock库
	if (WSACleanup() != 0)
	{
		printf(_T("卸载WinSock库失败,错误码为:%d\n"), WSAGetLastError());
		_gettchar();
		return 0;
	}
	_gettchar();
}

你可能感兴趣的:(Windows,计算机网络)