getaddrinfo関数のWinsockでの使用方法
1451 ワード
#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
"), nRet);
_gettchar();
return 0;
}
char hostName[256] = {0};
//
if (gethostname(hostName, 256) != 0)
{
_tprintf(_T(" , :%d
"), WSAGetLastError());
goto UNLOAD;
}
else
printf(" :%s
",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
"), nRet);
else
{
struct addrinfo *pAi;
printf(" IPv4 :
");
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
",pszIp);
}
}
UNLOAD:
// WinSock
if (WSACleanup() != 0)
{
printf(_T(" WinSock , :%d
"), WSAGetLastError());
_gettchar();
return 0;
}
_gettchar();
}