Getaddrinfo使用测试

来源:互联网 发布:网络推广服务 编辑:程序博客网 时间:2024/06/05 06:47
// 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#endifusing namespace std;int _tmain(int argc, _TCHAR* argv[]){  WORD wVersionRequested;WSADATA wsaData;int err;// Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.hwVersionRequested = 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;}

原创粉丝点击