// TestGetaddrinfo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//
//
//int _tmain(int argc, _TCHAR* argv[])
//{
// return 0;
//}
#include <stdio.h>
#include <stdlib.h>
#include <ws2tcpip.h>
#include <WinSock2.h>
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
// Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
struct addrinfo hints;
struct addrinfo *result;
struct addrinfo *res;
int error;
int sfd, s;
char service[NI_MAXSERV];
// Obtain address(es) matching host/port
_itoa_s(22000,service,10);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP;
error = getaddrinfo("idea-PC-chenjj", service, &hints, &result);
if (error != 0)
{
if (error == 11001)
{
perror("getaddrinfo");
}
else
{
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
}
exit(EXIT_FAILURE);
}
/* loop over all returned results and do inverse lookup */
for (res = result; res != NULL; res = res->ai_next)
{
char hostname[NI_MAXHOST] = "";
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);
if (error != 0)
{
fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error));
continue;
}
if (*hostname != '\0')
printf("hostname: %s\n", hostname);
}
freeaddrinfo(result);
WSACleanup();
return 0;
}
Getaddrinfo使用测试
最新推荐文章于 2023-06-27 11:50:34 发布