// TestGetaddrinfo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #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); } if((hostinfo = gethostbyname(name)) != NULL) { //这是获取主机名,如果获得主机名成功的话,将返回一个指针,指向hostinfo,hostinfo //为PHOSTENT型的变量,下面即将用到这个结构体 ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list); freeaddrinfo(result); WSACleanup(); return 0; }
getaddrinfo test
最新推荐文章于 2023-07-13 12:48:43 发布