getaddrinfo test

本文介绍了一个基于C++的控制台应用程序示例,该程序利用Winsock库中的getaddrinfo函数实现网络地址解析,并演示了如何进行主机名与IP地址之间的转换。通过具体代码展示了初始化Winsock、获取地址信息及进行逆向查找的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值